Sub topic 11
Async logic with createAsyncThunk
This chapter assumes you can write a slice with createSlice, build a store with configureStore, and read state in components with useSelector and useDispatch. It also assumes you know async/await and fetch. By the end you will be able to load data, track its loading and error state, and handle failures in components.
The problem thunks solve
Reducers must be pure. They cannot call fetch, wait on a timer, or read the clock. Async work has to happen somewhere else, and its results then have to reach the store as ordinary actions.
A thunk is a function you dispatch instead of an action object. Redux Toolkit's default middleware, which configureStore adds for you, notices a dispatched function and calls it with dispatch and getState. Writing the pending, success and failure actions by hand is repetitive. createAsyncThunk does it for you.
A first thunk
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.reducercreateAsyncThunk takes two required arguments:
- A type prefix, here
'todos/fetchTodos'. It becomes the base of three generated action types. - A payload creator, an async function. Its return value becomes
action.payloadof the fulfilled action. If it throws or returns a rejected promise, the rejected action is dispatched.
The slice listens with extraReducers because these actions belong to the thunk, not to a reducer defined in this slice. The builder.addCase form is the standard one, and it gives TypeScript the action types.
The lifecycle
Each dispatch of the thunk produces exactly one pending action, followed by exactly one fulfilled or rejected action.
The three action types are the prefix plus /pending, /fulfilled and /rejected. Every one carries meta with these fields:
meta.requestId: a unique ID for this run.meta.arg: the argument you passed when dispatching.
Use these to tell concurrent runs apart or to find which item a request was about.
Dispatching from a component
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { fetchTodos } from './todosSlice'
export 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.text}</li>
))}
</ul>
)
}The status string ('idle', 'loading', 'succeeded', 'failed') is a small state machine. It is easier to reason about than separate isLoading and hasError booleans, which can contradict each other.
Arguments and the thunk API
The payload creator receives two parameters: the argument given at dispatch, and a thunkAPI object. Pass several values by bundling them into one object, because only one argument is supported.
import { createAsyncThunk } from '@reduxjs/toolkit'
export const addTodo = createAsyncThunk(
'todos/addTodo',
async (text, { rejectWithValue }) => {
const response = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
})
if (!response.ok) {
const body = await response.json()
return rejectWithValue(body)
}
return response.json()
}
)Useful thunkAPI members:
| Member | Purpose |
|---|---|
| `dispatch` | Dispatch other actions or thunks from inside the thunk |
| `getState` | Read the current store state, for example to get an auth token |
| `signal` | An `AbortSignal` you can pass to `fetch` to support cancellation |
| `rejectWithValue` | Reject with a custom payload of your choosing |
| `requestId` | The unique ID of this run, also found in `meta` |
Errors: two kinds of rejection
If the payload creator throws, Redux Toolkit converts the error into a plain object (name, message, stack, code) and puts it in action.error. The conversion exists because the Redux store should only hold serializable values, and Error instances are not serializable.
If you call return rejectWithValue(body), the rejected action gets action.payload = body instead. Use this when the server sends structured errors, such as validation messages per field. A reducer then handles both cases:
.addCase(addTodo.rejected, (state, action) => {
state.status = 'failed'
state.error = action.payload?.message ?? action.error.message
})Using the result in the component with unwrap
dispatch(thunk()) returns a promise that always resolves, even when the thunk was rejected. It resolves to the final action. That is inconvenient when a component wants to react to the outcome, for example to clear a form only on success. Call .unwrap() on the returned promise. It resolves with the payload on success and throws on failure. What it throws is the rejectWithValue payload if you used one, or the serialized error otherwise.
import { useState } from 'react'
import { useDispatch } from 'react-redux'
import { addTodo } from './todosSlice'
export function AddTodoForm() {
const dispatch = useDispatch()
const [text, setText] = useState('')
const [error, setError] = useState(null)
async function handleSubmit(event) {
event.preventDefault()
try {
await dispatch(addTodo(text)).unwrap()
setText('')
setError(null)
} catch (err) {
setError(err?.message ?? 'Could not add todo')
}
}
return (
<form onSubmit={handleSubmit}>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button type="submit">Add</button>
{error && <p>{error}</p>}
</form>
)
}Local state such as the form text and its error message stays in useState. It is not shared, so it does not belong in the store.
Preventing duplicate requests with condition
The useEffect guard in TodoList has a gap. In development, React Strict Mode runs effects twice on mount. Both runs see status === 'idle' from the same render, so the thunk is dispatched twice. The same happens when two components request the same data at once.
The third argument to createAsyncThunk is an options object. Its condition callback runs before the payload creator and can cancel the whole run:
import { createAsyncThunk } from '@reduxjs/toolkit'
export const fetchTodos = createAsyncThunk(
'todos/fetchTodos',
async (_, { signal }) => {
const response = await fetch('/api/todos', { signal })
if (!response.ok) {
throw new Error('Request failed')
}
return response.json()
},
{
condition: (_, { getState }) => getState().todos.status !== 'loading',
}
)When condition returns false, no pending, fulfilled or rejected action is dispatched. Set dispatchConditionRejection: true in the options if you want a rejected action with meta.condition: true instead.
This version also passes signal to fetch. The promise returned by dispatch(fetchTodos()) has an abort() method. Calling it, for example in an effect cleanup, aborts the request and dispatches a rejected action with error.name === 'AbortError'.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Not checking `response.ok` | HTTP errors appear as success | Throw or `rejectWithValue` on `!response.ok` |
| Passing two arguments at dispatch | The second one is ignored | Pass one object: `fetchUser({ id, force })` |
| Putting `Error` objects or `Date` instances in the payload | Serializability warnings in development | Return plain data such as strings, numbers and ISO date strings |
| Forgetting `.unwrap()` in a `try/catch` | The `catch` never runs | Call `.unwrap()` on the dispatch result |
| Handling the thunk in `reducers` instead of `extraReducers` | The reducer never fires | Use `extraReducers` with `builder.addCase` |
| Ignoring stale responses | An older request can overwrite newer data | Compare `action.meta.requestId` or `arg`, or use `condition` |
Exercise
A deleteTodo thunk calls DELETE /api/todos/:id. The server answers 404 with the JSON body {"message": "Not found"}. You want the component to show "Not found" in an error message. What do you write in the payload creator, and how does the component read the message?
Show answer
In the payload creator, check if (!response.ok), then read the body with const body = await response.json() and return rejectWithValue(body). In the component, wrap await dispatch(deleteTodo(id)).unwrap() in try/catch. The catch receives the rejectWithValue payload, so err.message is "Not found". In a slice reducer for deleteTodo.rejected, the same text is in action.payload.message.
Exercise
Why does useEffect(() => { if (status === 'idle') dispatch(fetchTodos()) }, [status, dispatch]) still send two requests under React Strict Mode in development, and what is the smallest change that stops it?
Show answer
Strict Mode runs the effect twice after the first render. Both runs use the same status value, 'idle', because the store update from the first dispatch has not caused a re-render yet. Add condition: (_, { getState }) => getState().todos.status !== 'loading' to the thunk options. The second dispatch then sees 'loading' in the store and is skipped without dispatching any actions.