I'm wondering how to use async action creators in mapDispatchToProps
for react-redux
's connect
. I'm using the redux-thunk
middleware and the following is my mapDispatchToProps
:
function mapDispatchToProps(dispatch) {
return {
foo: function() {
dispatch(someAction());
return function asyncAction(dispatch, getState) {
console.log("An async action!");
dispatch(someOtherAction(getState().foo));
};
}
}
}
However, when I do the above, the async action does not get executed. What is the correct way to do this?
I suggest declaring your actual thunk (someOtherAction
) differently. In the following example, asyncAction
is an async action creator which returns a thunk. The thunk can then dispatch other actions (after a promise resolves for example).
function asyncActionCreator () {
return (dispatch, getState) => {
dispatch(someAction());
someAsyncStuff().then(() => {
dispatch(someOtherAction(getState().foo);
});
}
}
function mapDispatchToProps(dispatch) {
return {
foo: () => dispatch(asyncActionCreator())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With