A todo list shows the right results for a moment, then flips back to the old ones. There's no error in the console, and every test passes.
I ran into this while fixing an issue in an open source React + Redux Toolkit app. Two fetchTodos requests were in flight at the same time, the older one answered last, and the reducer wrote its result over the newer one. Here is the bug, two variants of it that are easy to miss, the fix, and how to test it without fake timers.
The bug
This is the slice most of us write for a list:
export const fetchTodos = createAsyncThunk(
'todos/fetchAll',
(filters: TodoFilters) => todosApi.getAll(filters),
);
// in the slice
builder
.addCase(fetchTodos.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchTodos.fulfilled, (state, action) => {
state.status = 'idle';
state.items = action.payload.data;
state.total = action.payload.meta.total;
})
.addCase(fetchTodos.rejected, (state) => {
state.status = 'error';
});
Nothing here links a response to the request the UI is waiting for. Whichever response resolves last wins, not whichever request started last.
That happens more often than you'd think:
- The user types in a search box:
a, thenab. Theaquery is slower (more results) and returns afterab. - They click through pages quickly.
- You refetch on window focus while a filter change is still loading.
- The first request hits a cold cache or a slow network; the second one doesn't.
The result is a list that doesn't match the filter on screen. It's hard to reproduce because it depends on timing.
Two variants people miss
A stale error. The old request fails after the new one has already succeeded. The data on screen is correct, but status is now 'error', so the UI shows an error banner over good data.
A response that arrives after logout. A fetch starts, the user logs out, and the slice resets to its initial state:
.addCase(logout, () => initialState)
Then the response arrives, fulfilled runs, and the reset state is filled with the previous user's list. If the next person signs in on the same tab, they can see it. Of the three, this is the one I'd fix first.
The fix: action.meta.requestId
createAsyncThunk gives every dispatch a unique requestId. It's on action.meta for pending, fulfilled and rejected, so all three actions of one dispatch share it.
Store the id when a request starts, and ignore any result whose id doesn't match:
builder
.addCase(logout, () => initialState)
.addCase(fetchTodos.pending, (state, action) => {
state._fetchTodosRequestId = action.meta.requestId;
state.status = 'loading';
})
.addCase(fetchTodos.fulfilled, (state, action) => {
// an older request answering late (or one started before logout)
// must not overwrite the list
if (action.meta.requestId !== state._fetchTodosRequestId) return;
state.status = 'idle';
state.items = action.payload.data;
state.total = action.payload.meta.total;
})
.addCase(fetchTodos.rejected, (state, action) => {
if (action.meta.requestId !== state._fetchTodosRequestId) return;
state.status = 'error';
});
All three cases are handled:
-
Reverse order: the second
pendingoverwrites the stored id, so the first response no longer matches. -
Stale error: same check in
rejected. -
Logout:
initialStatehas no stored id, so a response from before the reset can't match.
I named the field with a leading underscore and typed it as optional. It's bookkeeping, not UI state, and no component should read it.
Testing it without timers
You don't need fake timers or setTimeout in the mock. Return a promise you resolve yourself, then resolve the requests in the order you want:
it('keeps the latest request when two resolve in reverse order', async () => {
let resolveFirst: (value: TodosResponse) => void = () => undefined;
vi.mocked(todosApi.getAll)
.mockReturnValueOnce(
new Promise((resolve) => {
resolveFirst = resolve;
}),
)
.mockResolvedValueOnce({ data: [todoB], meta: { total: 1 /* ... */ } });
const store = makeTodosStore();
const first = store.dispatch(fetchTodos({ ...filters, query: 'a' }));
await store.dispatch(fetchTodos({ ...filters, query: 'ab' }));
resolveFirst({ data: [todoA, todoB], meta: { total: 2 /* ... */ } });
await first;
expect(store.getState().todos.items).toEqual([todoB]);
expect(store.getState().todos.status).toBe('idle');
});
The other two tests follow the same pattern:
-
Stale error: call
rejecton the first promise after the second request succeeds, and check thatstatusis still'idle'. -
Logout: dispatch
logout()between starting the fetch and resolving it, and check thatitemsis still empty.
To check the tests themselves, I put the reducer back to the version without the guard. All three new tests failed and the rest of the suite still passed. That's how I know they test the race and not something else.
Alternatives, and when to pick them
| Approach | Stops the stale write | Cancels the request | Cost |
|---|---|---|---|
requestId guard in the reducer |
yes | no | a few lines |
promise.abort() on the previous dispatch |
yes: it ends right away as rejected with meta.aborted, and its fulfilled never runs |
only if the thunk passes thunkAPI.signal to fetch
|
you have to keep the handle and remember to call it |
condition option |
skips starting a new fetch | — | wrong here: the newer request has new filters |
| RTK Query | yes | yes | moving the endpoint over |
If you can move the endpoint to RTK Query, do that. It caches each argument separately, so a slow a response can't replace the ab results. Abort and the guard work well together. Abort saves the network call, and the guard still protects you anywhere someone forgot to abort.
Limits
- The guard is in the reducer only. The stale
rejectedaction still reaches middleware, so a global "show an error toast on any rejected action" listener will still fire. If you have one, apply the same check there or skip rejected actions whose request is no longer current. - I used one id per thunk type. If two parts of the screen use the same thunk for different lists at the same time, they will cancel each other's results. Then you need one id per list, keyed by something in
action.meta.arg.
The rule I keep now
If a reducer writes the result of an async call, it should first check whether this is still the request the UI is waiting for. With createAsyncThunk that check is a single line.
How do you handle this in your apps: abort, a request id, or RTK Query everywhere?
Top comments (2)
One id per thunk type gets awkward. Search and pagination firing the same thunk against different lists means each one cancels the other's results, so the guard needs a key from action.meta.arg before it's worth adding. Naming it _fetchTodosRequestId hides it from components but not from the next person wiring a second list to the same thunk. I'd fix logout first, since the guard there costs nothing extra.
Fair point. The post only mentions this under Limits, and if search and pagination share a thunk, that's too late. The keyed version is small: in
pending, storestate.requestIds[action.meta.arg.listKey] = action.meta.requestId, and compare against the same key infulfilledandrejected. Logout still works becauseinitialStatestarts with an empty map.One caveat: if both callers write into the same
items, they're really one list, and a single id is right, since the newest request should win. The key only matters once each list has its own state.You're right about the name too. The underscore tells components not to read it, but it tells nothing to the next person who adds a second caller. A one-line comment on the thunk ("one in-flight request per listKey") would do more than the naming.
And agreed on logout first. It's the only one of the three that leaks data between users, and the guard fixes it at no extra cost.