brennie brennie - 1 month ago 32
React JSX Question

Using thunks in mapDispatchToProps

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 executed. What is the correct way to do this?

Answer

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())
  }
}