Search code examples
javascriptredux

Where to dispatch multiple actions in redux?


I am using redux with connect and redux-thunk middleware and containers.

Currently when a user perform an action, example one click on a button, I need to dispatch that action (sync) which will dispatch other few actions (asynch).

I am aware dispatching actions from within the reducer is an anti pattern.

I would like to know what is a suitable place for this code.

Currently I am not sure if it should stay in:

  • The action creator.
  • In the container using store.subscribe.

Solution

  • The recommended way as per the documentation is in the action creator, like so:

    function actionCreator(payload) {
        return dispatch => {
            dispatch(action1(payload))
            dispatch(action2(payload))
        }
    }
    

    Then you would probably want to attach the action creators as prop and pass it down to the container using mapDispatchToProps like in the example mentioned here. So it would look something like so:

    const mapDispatchToProps = dispatch => ({
       action1: some_payload => dispatch(action1(some_payload))
       action2: some_payload => dispatch(action2(some_payload))
    })
    
    // your component
    export default connect(mapStateToProps, mapDispatchToProps)(YourApp)