Home > OS >  How to update my redux store synchronously?
How to update my redux store synchronously?

Time:03-21

I have a function that is being dispatched twice in small time duration. Suppose 1st call was made on time X and second call was made on time Y. Where Y > X and difference between X and Y is 5 millisecond or less.

Call made at time Y is updating the store 1st and then call made at time X. So my store is being updated with outdated data. How to overcome this situation ?

I am using redux-thunk.

CodePudding user response:

I'm assuming your problem is that the result for the first async call arrives after the result for the second async call (which has priority) has already arrived.

The general idea to deal with this is that you need to be able to keep track of the latest/most recent call, versus the other, outdated calls that should be ignored and not affect the state anymore.

To solve this, save the value of Date.now() in your state to remember when the most recent request started. In thunks you have access to getState, so you can check if the current request is still the one that has most recently started.

Pseudo code:

const myThunk = () => async (dispatch, getState) => {
    const startedAt = Date.now();

    // this needs to write state.mostRecentRequestStartedAt = action.payload.startedAt; in the reducer
    dispatch(requestStarted(startedAt));
    
    const result = await doSomethingAsync();

    // At this point, other more recent requests might have started!
    const { mostRecentRequestStartedAt } = getState();
    if (startedAt === mostRecentRequestStartedAt) {
        dispatch(saveResult(result));
    } else {
        // result is from an outdated request. Ignore it or do something else here.
    }
};
  • Related