Skip to content

Instantly share code, notes, and snippets.

@Rajatgms
Created August 3, 2020 17:59
Show Gist options
  • Save Rajatgms/dfb11ff1e399bcaf0cb3495b30f17101 to your computer and use it in GitHub Desktop.
Save Rajatgms/dfb11ff1e399bcaf0cb3495b30f17101 to your computer and use it in GitHub Desktop.
Use request ID to control state
const loaderSlice = createSlice({
name: 'loader',
initialState: {
loading: 'idle',
currentRequestId: undefined,
},
reducers: {},
extraReducers: {
[fetchUserById.pending]: (state, action) => {
if (state.loading === 'idle') {
state.loading = 'pending'
state.currentRequestId = action.meta.requestId
}
},
[fetchUserById.fulfilled]: (state, action) => {
const { requestId } = action.meta
if (state.loading === 'pending' && state.currentRequestId === requestId) {
state.loading = 'idle',
state.currentRequestId = undefined
}
},
[fetchUserById.rejected]: (state, action) => {
const { requestId } = action.meta
if (state.loading === 'pending' && state.currentRequestId === requestId) {
state.loading = 'idle'
state.currentRequestId = undefined
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment