Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispatch multiple actions one after another

Tags:

reactjs

redux

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-thunkto build an action creator like this

function loginRequestSuccess(data) {   return function(dispatch) {     dispatch(saveUserData(data.user))     dispatch(loadConfig())   } } 

So my questions are:

  1. When the first dispatchreturns, is the state already changed by all reducers listening for that action? I'm wondering if the two dispatch calls are run strictly sequential.
  2. Is this approach considered best practice for dispatching multiple actions? If not, what would you suggest alternatively?

Thanks for any help!

like image 216
Steve Avatar asked Jul 27 '16 14:07

Steve


People also ask

Can I dispatch more than one action?

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.

Does Redux support multiple actions?

In Redux, actions are the JavaScript object which has information. Having multiple actions will need multiple action creators.

Can we dispatch actions from reducers?

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.


1 Answers

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.

like image 61
John Avatar answered Sep 23 '22 10:09

John