0
votes

My assumption from working with redux is that dispatching actions is a synchronous task.

fire action 1 - > store updated
fire action 2 -> store updated

In a project I'm currently working on, I have a product customizer, that allows some user selection, they can place multiple orders, but if they're only ordering their current selection and select "purchase", I fire "addOrder", adding their selection to the orders array, and then the "purchase" action, which is a thunk submitting the orders stored in redux to my cart API.

I've expected that I would be able to rely on the store being in a consistent state, reliably after each action, and so when that second action fires it would have the state, as it is, after the first regular action fired before it, but no dice.

  • Are my expectations and understanding of redux here incorrect?
  • If so, Is redux thunk acting outside the normal dispatch in some way?

in my connected component I dispatch each action:

//.... inside component
purchase = () => {
  this.props.addOrder(); // regular action
  this.props.purchase(); // thunk
};
// ... rest of component
1
Can you provide a repo or codesandbox.io example of this not working? It definitely sounds like an extra middleware in the stack is injecting some asynchronicity into your store. - Tim Dorr
I am facing the same problem, did you figure out why is this happening? - aryan

1 Answers

8
votes

Yes, dispatching is always 100% synchronous, unless altered by a middleware. And yes, by default, you can call getState() again after a dispatch to get the updated state:

function checkStateAfterDispatch() {
    return (dispatch, getState) => {
        const firstState = getState();
        dispatch({type : "FIRST_ACTION"});

        const secondState = getState();

        if(secondState.someField != firstState.someField) {
            dispatch({type : "SECOND_ACTION"});
        }    
    }
}