Skip to content

Commit ce8b8af

Browse files
committed
Fix bug in docs for createAsyncThunk example
fetchUserById payloadCreator should fetch when in pending (not idle) state
1 parent 36b25fc commit ce8b8af

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

docs/api/createAsyncThunk.md

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -325,9 +325,9 @@ import { userAPI } from './userAPI'
325325

326326
const fetchUserById = createAsyncThunk(
327327
'users/fetchByIdStatus',
328-
async (userId, { getState }) => {
329-
const { loading } = getState().users
330-
if (loading !== 'idle') {
328+
async (userId, { getState, requestId }) => {
329+
const { currentRequestId, loading } = getState().users
330+
if (loading !== 'pending' || requestId !== currentRequestId) {
331331
return
332332
}
333333
const response = await userAPI.fetchById(userId)
@@ -340,25 +340,31 @@ const usersSlice = createSlice({
340340
initialState: {
341341
entities: [],
342342
loading: 'idle',
343+
currentRequestId: undefined,
343344
error: null
344345
},
345346
reducers: {},
346347
extraReducers: {
347348
[fetchUserById.pending]: (state, action) => {
348349
if (state.loading === 'idle') {
349350
state.loading = 'pending'
351+
state.currentRequestId = action.meta.requestId
350352
}
351353
},
352354
[fetchUserById.fulfilled]: (state, action) => {
353-
if (state.loading === 'pending') {
355+
const { requestId } = action.meta
356+
if (state.loading === 'pending' && requestId === state.currentRequestId) {
354357
state.loading = 'idle'
355-
state.push(action.payload)
358+
state.entities.push(action.payload)
359+
state.currentRequestId = undefined
356360
}
357361
},
358362
[fetchUserById.rejected]: (state, action) => {
359-
if (state.loading === 'pending') {
363+
const { requestId } = action.meta
364+
if (state.loading === 'pending' && requestId === state.currentRequestId) {
360365
state.loading = 'idle'
361366
state.error = action.error
367+
state.currentRequestId = undefined
362368
}
363369
}
364370
}

0 commit comments

Comments
 (0)