Sub topic 10
Handling actions from other slices with extraReducers
This chapter assumes you can write a slice with createSlice, know that Immer lets reducers "mutate" draft state, and understand that every dispatched action reaches every reducer in the store.
Why reducers sometimes need outside actions
The reducers field of createSlice defines actions that the slice owns. For each entry, RTK generates an action creator, and its type is prefixed with the slice name, such as counter/incremented.
Sometimes a slice must react to an action it did not define. Common cases:
- A thunk dispatches
pending,fulfilledandrejectedactions. - Another slice's action should also change this slice, for example logging out should clear the todos.
- An RTK Query or entity adapter action needs a response.
extraReducers handles these cases. Entries in extraReducers respond to actions but do not generate new action creators.
The builder callback
Pass extraReducers a function that receives a builder object. Call builder.addCase(actionCreator, reducer) for each action to handle.
import { createSlice } from '@reduxjs/toolkit'
import { userLoggedOut } from './authSlice'
const todosSlice = createSlice({
name: 'todos',
initialState: { items: [], filter: 'all' },
reducers: {
todoAdded(state, action) {
state.items.push(action.payload)
},
},
extraReducers: (builder) => {
builder.addCase(userLoggedOut, (state) => {
state.items = []
state.filter = 'all'
})
},
})
export const { todoAdded } = todosSlice.actions
export default todosSlice.reducerHere userLoggedOut is an action creator exported from another slice. RTK reads its type string, so you pass the creator itself and never write the string by hand. The reducer body works like any other: Immer applies, and you can mutate state.
Handling thunk lifecycle actions
A thunk created with createAsyncThunk exposes pending, fulfilled and rejected action creators. You attach them with addCase, as in the async chapter that follows. The same pattern applies to any action creator.
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
export const loadProfile = createAsyncThunk('profile/load', async (id) => {
const response = await fetch(`/api/users/${id}`)
if (!response.ok) throw new Error('Request failed')
return response.json()
})
const profileSlice = createSlice({
name: 'profile',
initialState: { data: null, status: 'idle' },
reducers: {},
extraReducers: (builder) => {
builder
.addCase(loadProfile.pending, (state) => {
state.status = 'loading'
})
.addCase(loadProfile.fulfilled, (state, action) => {
state.status = 'succeeded'
state.data = action.payload
})
},
})
export default profileSlice.reduceraddCase calls chain, so you can handle several actions in one builder.
Other builder methods
The builder has two more methods. Call them in this order: all addCase calls first, then addMatcher, then addDefaultCase.
| Method | Purpose |
|---|---|
| `addCase(creator, reducer)` | Handle one specific action type. |
| `addMatcher(predicate, reducer)` | Handle every action for which a function returns true. |
| `addDefaultCase(reducer)` | Run when no other case or matcher handled the action. |
A matcher is useful for shared behavior. For example, builder.addMatcher((action) => action.type.endsWith('/rejected'), (state) => { state.error = true }) marks failure for any rejected thunk.
Common errors
- Adding cases after a matcher. RTK throws an error if
addCaseappears afteraddMatcheroraddDefaultCase. - Importing in a circle. If slice A imports an action from slice B and B imports from A, you can get
undefinedat startup. Move shared actions into their own file, or have one slice depend on the other in only one direction. - Expecting an action creator to exist.
extraReducersdoes not add entries toslice.actions. Export the action from the slice that owns it. - Handling the same type twice. A case reducer for a type that the slice already defines in
reducersthrows an error in development.
Exercise
A cart slice must empty its items array whenever userLoggedOut from the auth slice is dispatched. Where do you write this logic, and why not in reducers?
Show answer
Write it in extraReducers with builder.addCase(userLoggedOut, (state) => { state.items = [] }). The reducers field is for actions the cart slice owns and generates creators for. userLoggedOut belongs to the auth slice, so the cart slice only listens to it.
Exercise
What does RTK do if you call builder.addCase after builder.addMatcher?
Show answer
It throws an error. Calls must be ordered: all addCase, then addMatcher, then addDefaultCase.