In my react / redux application I often want to dispatch multiple actions after another.
Given the following example: After a successful login I want to store the user data and after that I want to initiate another async action that loads application configuration from the server.
I know that I can use redux-thunk
to build an action creator like this
function loginRequestSuccess(data) { return function(dispatch) { dispatch(saveUserData(data.user)) dispatch(loadConfig()) } }
So my questions are:
dispatch
returns, is the state already changed by all reducers listening for that action? I'm wondering if the two dispatch calls are run strictly sequential.Thanks for any help!
The answer of course is, yes, just either call dispatch multiple times or iterate dispatch over an array. Usually, though, if you're dispatching multiple actions like that, it's a sign that you might want to look into creating yet another action to better encode the intent behind the cause of all those other actions.
In Redux, actions are the JavaScript object which has information. Having multiple actions will need multiple action creators.
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
Yes redux-thunk allows you to do as you say, and yes it is a best practice for dispatching multiple actions (one that I prefer over the alternatives because of it's simplicity). The state is indeed updated as soon as you dispatch (by the time it returns), which is why you are given a function to retrieve the state in a thunk, instead of simply a reference to the state. In that way you can alter the state with one dispatch, and then call getState() to get a reference to the new state to read from if you need to.
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