Sub topic 11
Async logic with createAsyncThunk
This chapter assumes you can write a slice with createSlice, configure a store, and use useSelector and useDispatch. It also assumes you know fetch, promises, and async/await. The goal is to load data from a server and track the request in the store.
Why reducers can't do async work
A reducer must be a pure function. It can't call fetch or wait on a promise. Async work has to happen outside the reducer, and the result goes into the store as an action.
A thunk is a function that you dispatch in place of a plain action object. The store's middleware runs it and gives it dispatch and getState. Redux Toolkit's configureStore includes the thunk middleware by default.
createAsyncThunk wraps this pattern. You give it an action type prefix and a function that returns a promise. It dispatches actions for each stage of the request, so you don't write them by hand.
The request lifecycle
Defining a thunk and handling its actions
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
export const fetchTodos = createAsyncThunk('todos/fetchTodos', async () => {
const response = await fetch('/api/todos')
if (!response.ok) {
throw new Error('Request failed')
}
return response.json()
})
const todosSlice = createSlice({
name: 'todos',
initialState: { items: [], status: 'idle', error: null },
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchTodos.pending, (state) => {
state.status = 'loading'
})
.addCase(fetchTodos.fulfilled, (state, action) => {
state.status = 'succeeded'
state.items = action.payload
})
.addCase(fetchTodos.rejected, (state, action) => {
state.status = 'failed'
state.error = action.error.message
})
},
})
export default todosSlice.reducerThe first argument, 'todos/fetchTodos', is the prefix. The thunk creates three action types from it: todos/fetchTodos/pending, todos/fetchTodos/fulfilled, and todos/fetchTodos/rejected.
The payload creator is the async function. Whatever it returns becomes action.payload on the fulfilled action. If it throws, the rejected action carries a serialized error in action.error.
The slice can't list these actions in reducers, because they belong to the thunk. You handle them in extraReducers, using the builder's addCase. The status field (idle, loading, succeeded, failed) is a common way to describe where the request is.
Dispatching from a component
Dispatch the thunk like any other action. Fetch on mount, and only when nothing has been requested yet:
import { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { fetchTodos } from './todosSlice'
function TodoList() {
const dispatch = useDispatch()
const items = useSelector((state) => state.todos.items)
const status = useSelector((state) => state.todos.status)
const error = useSelector((state) => state.todos.error)
useEffect(() => {
if (status === 'idle') {
dispatch(fetchTodos())
}
}, [status, dispatch])
if (status === 'loading') return <p>Loading...</p>
if (status === 'failed') return <p>Error: {error}</p>
return (
<ul>
{items.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}
export default TodoListThe status === 'idle' check prevents a second request when the component re-renders or mounts again.
Arguments and return values
The payload creator receives the argument you pass when dispatching, plus a thunkAPI object. It can only take one argument, so pass an object if you need several values.
export const fetchTodoById = createAsyncThunk(
'todos/fetchTodoById',
async (id, { rejectWithValue }) => {
const response = await fetch(`/api/todos/${id}`)
if (!response.ok) {
return rejectWithValue({ status: response.status })
}
return response.json()
}
)rejectWithValue lets you control the rejected payload. It then arrives as action.payload, not action.error. thunkAPI also provides getState, dispatch, and signal for cancellation.
dispatch returns a promise. Call .unwrap() on it to get the payload on success or to throw on failure:
try {
const todo = await dispatch(fetchTodoById(7)).unwrap()
console.log(todo.title)
} catch (err) {
console.log('Failed with status', err.status)
}Common errors
- Putting the thunk's cases in
reducersinstead ofextraReducers. They will never run. - Forgetting to throw on
!response.ok, so failures look like successes. - Reading
action.errorwhen you usedrejectWithValue. Readaction.payloadinstead. - Dispatching in an effect without a guard, which can trigger repeated requests.
- Passing two positional arguments to the thunk. Only the first reaches the payload creator.
Exercise
A thunk's payload creator fetches /api/todos and the server answers with status 500. The code does not check response.ok and calls response.json() on an HTML error page. Which lifecycle action is dispatched, and what would change if the code checked response.ok and threw?
Show answer
Without the check, fetch resolves normally. response.json() then fails on the HTML body and throws, so rejected is dispatched, but with a confusing parse error. If the body happened to be valid JSON, fulfilled would be dispatched with the error body as the payload. With the check, the thunk throws Error('Request failed'), rejected is dispatched, and action.error.message is 'Request failed'.