Reputation: 1341
I am using ducks with Redux, but that should be irrelevant to the question. I have a couple of action creators in the same file and I want to invoke one from within the other (hopefully without having to double dispatch for every CASE in the SWITCH below):
...
export function closeAuthDialogs() {
return {type: CLOSE_AUTH_DIALOGS}
}
export function openDialog(dialog) {
// close any open dialogs
dispatch => {dispatch(closeAuthDialogs())} // <--THIS DOES NOT GET CALLED!!!
//open the one we need
switch (dialog) {
case 'login':
return {type: OPEN_LOGIN}
case 'register':
return {type: OPEN_REGISTER}
case 'forgot':
return {type: OPEN_FORGOT}
case 'change':
return {type: OPEN_CHANGE}
case 'profile':
return {type: OPEN_PROFILE}
default:
return;
}
}
...
The opens work fine, but the close function never gets fired. Is there a way to invoke the close function from within the open function without double dispatching for each CASE in the SWITCH of the open function?
By double dispatching I mean something like...
return dispatch => {
dispatch({type: CLOSE_AUTH_DIALOGS})
dispatch({type: OPEN_SOME_DIALOG)}
}
If possible, I'd like to only invoke the close once and then return the specified open.
TIA!
Upvotes: 1
Views: 262
Reputation: 7550
You need to use a middleware like redux-thunk. Installation instructions here but basically you need to apply it when you're setting up your store:
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
This will allow you to return a function from an action. Something like this should do it:
export function openDialog(dialog) {
return (dispatch) => {
dispatch(closeAuthDialogs());
switch (dialog) {
case 'login':
return dispatch({type: OPEN_LOGIN})
case 'register':
return dispatch({type: OPEN_REGISTER})
case 'forgot':
return dispatch({type: OPEN_FORGOT})
case 'change':
return dispatch({type: OPEN_CHANGE})
case 'profile':
return dispatch({type: OPEN_PROFILE})
default:
return;
}
}
}
Upvotes: 3