I am using redux with connect
and redux-thunk
middleware and containers.
Currently when an 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.
The action creator is the correct location for dispatching multiple actions. Although code like the following would work:
I would highly recommend
redux-thunk
based action creators to always return a resolved Promise, so that such action creators can be part of another async call. So, the simplest update to the above would be:It would then be possible to dispatch to the above with:
actionCreator(payload).then(doAnotherAction(anotherPayload))
or the following, if we need to maintain order of calls:actionCreator(payload).then(() => doAnotherAction(anotherPayload))
If you wish to 'future-proof' your action creator, so that it could handle calling both async and sync action creators, you could write it as:
And, if you like ES6 arrow notation the above can be defined as:
While solution by @GibboK did not work for me:
I eventually went with redux-batched-actions. Worked like charm:
The easiest way is to use a specialized middleware redux-soldier:
redux-soldier
is also a full replacement forredux-thunk
For more info check the documentation redux-soldier.
The recommended way as per the documentation is in the action creator, like so:
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:If you have a Promise Middleware, you can use this syntax so you're able to use
.then()
on yourdispatch(topLevelAction())
:As other pointed out
The action creator
is the right place for dispatching multiple actions.Below an example of how
action1
could dispatch other actions in youraction creator
.