does changes to redux store occur synchronous? [duplicate]
Asked Answered
S

1

6

si it guaranteed that by time store.dispatch returns, the state has already changed? and if thats case, then why not return newState as a result of dispatch call?

store.dispatch( action1() );
store.dispatch( action2() );

an example I will login user in action1, then i want to fire another action that will use the LOGEDIN user information to change the state further more. so i want to make sure that action2 will not fire unless action1 has already changed the state successfully.

so, by time store.dispatch returns, is this garanteed that the state has already changed ?

example reducer:

function reducer(state, action){
  // please ignore that i will mutate state, just for sake of simplicity of example.
  if(action.type==='ACTION1'){
   state.user_id = action.payload;
   return state;
 } 

 if(action.type==='ACTION1'){
   state.value2 = state.user_id * action.whatEver;
   return state;
 }

  return state;
}

my current protection is i use React.component to monitor changes to user_id then i fire action2, but if Redux Actions are synchronous then i can fire action2 directly after action1 and just reduce my boilerplate.

Scheme answered 7/8, 2017 at 6:52 Comment(0)
C
13

Yes, by default dispatch() is 100% synchronous. Middleware can intercept actions and potentially delay them or modify behavior in some other asynchronous way. But,other than that, by the time dispatch returns, it is guaranteed that the root reducer has finished running, the current state value has been swapped out, and the subscribers have been notified.

Cierracig answered 7/8, 2017 at 15:51 Comment(1)
Is this always the case?Offprint

© 2022 - 2024 — McMap. All rights reserved.