//EDITED FOR CLARITY
I am trying to chain dispatches with redux thunk
function simple_action(){
return {type: "SIMPLE_ACTION"}
}
export function async_action(){
return function(dispatch, getState){
return dispatch(simple_action).then(()=>{...});
}
}
How do I get the dispatch to return a promise from the store?
MORE SPECIFICALLY:
I am probably just not understanding something here, but in all the examples with redux-thunk
, they call a separate async event (like fetch
), which obviously returns a Promise
.
What I'm specifically looking for is when I dispatch an action to the store: How do I make certain the store has processed that action completely before anything else happens in the function action_creator()
above.
Ideally, I would like the store to return some sort of promise, but I don't understand how or where that happens?
This is a pattern I've been using recently:
When you
dispatch(someThenableThunk('hello-world'))
, it returns aPromise
object that you can chain further actions to.Here you have an example on how to dispatch and chain async action. https://github.com/gaearon/redux-thunk
The thunk middleware knows how to turn thunk async actions into actions, so you just have to have your simple_action() to be a thunk and the thunk middleware will do the job for you, if the middleware see a normal action, he will dispatch this action as normal action but if it's an async function it will turn your async action into normal action.
So your simple_action need to be a thunk ( A thunk is a function that returns a function.) Like this for example:
When using the makeASandwichWithSecretSauce function you can use the dispatch function
And even
Here a complete example on how you can write action creators that dispatch actions and async actions from other action creators, and build your control flow with Promises.
//usage
To create you own promises you can use a library like bluebird.
//EDIT : To be sure that the store has processed that action completely before anything else happens in the function action_creator() you can dispatch this simple_action before action_creator(); // I added this comment to the code
//Do this action before starting the next one below
dispatch
will return whatever the action/function it calls returns; so if you want to chain certain activities (as per your example), your action would need to return aPromise
.As @Aaleks mentions, if your action were a
thunk
you can create a scenario where you return aPromise
, then you could do as you mention.BTW I think naming your
thunk
action_creator
is a bit misleading, assimple_action
is actually an Action Creator in Redux parlance - have edited accordingly :)