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.
}
};