Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 381
brennie Avatar asked Oct 12 '16 16:10

brennie


1 Answers

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())
  }
}
like image 187
Mario Tacke Avatar answered Sep 30 '22 00:09

Mario Tacke