Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 41 ยท Async Logic and Data Fetching

createAsyncThunk

Understand createAsyncThunk in Redux Toolkit: the pending, fulfilled and rejected actions, extraReducers, rejectWithValue, conditions, cancellation and unwrap.

Hand-written thunks all look alike: dispatch a "started" action, await something, dispatch "succeeded" or "failed". Redux Toolkit packages that pattern as createAsyncThunk. You give it an action-type prefix and an async function, and it returns a thunk creator plus three generated action creators.

This lesson explains what it generates, how a slice reacts to it with extraReducers, and the options you need in real projects. Because the Redux packages are not available in the editor, the runnable examples use a small stand-in that behaves like the real one for the basics; the real code is read-only.

The real API (read-only)

JavaScript
// Real Redux Toolkit code (read-only)
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

export const fetchTodos = createAsyncThunk('todos/fetch', async (userId, thunkApi) => {
  const res = await fetch(`/api/users/${userId}/todos`, { signal: thunkApi.signal });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();           // becomes action.payload of todos/fetch/fulfilled
});

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;
      });
  },
});

Three things to notice:

  1. The first argument, 'todos/fetch', is a prefix. The generated types are todos/fetch/pending, todos/fetch/fulfilled and todos/fetch/rejected.
  2. The payload creator receives one argument (what you pass when dispatching) and a thunkApi object with dispatch, getState, extra, requestId, signal, rejectWithValue and fulfillWithValue.
  3. The slice listens with extraReducers because these actions were not created by the slice's own reducers. Inside createSlice reducers you may "mutate" the state: Immer turns it into an immutable update (see Immutable updates and Immer).

A stand-in you can run

This stand-in recreates the mechanism in about twenty lines: it returns a thunk that dispatches pending, runs your function, then dispatches fulfilled or rejected with a request id, just like the real one.

JS createAsyncThunk stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The thunk always resolves with the final action (fulfilled or rejected) and never throws, which is a deliberate design: an unhandled rejection never leaks out of a dispatch. If you want a throwing promise, the real API provides .unwrap() (below).

Lifecycle and the meta object

Each generated action carries meta.requestId (unique per call) and meta.arg (what you passed in). The requestId lets a reducer ignore stale responses, a classic race-condition fix: store currentRequestId on pending and only accept a fulfilled whose id matches.

stateDiagram-v2
  [*] --> idle
  idle --> loading: pending
  loading --> succeeded: fulfilled
  loading --> failed: rejected
  failed --> loading: retry
  succeeded --> loading: refetch

The status machine that the three actions drive.

Handling errors with rejectWithValue

By default a thrown error becomes a serialized action.error (name, message, stack). When the server sends a useful body, such as validation errors, return it yourself:

JavaScript
// Real Redux Toolkit code (read-only)
export const createUser = createAsyncThunk('users/create', async (form, { rejectWithValue }) => {
  const res = await fetch('/api/users', { method: 'POST', body: JSON.stringify(form) });
  if (res.status === 422) return rejectWithValue(await res.json()); // action.payload on rejected
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
});

With rejectWithValue, the rejected action has action.payload (your value) and action.meta.rejectedWithValue === true. Without it, read action.error.message. Never put non-serializable values (Error objects, class instances, Response) into an action: Redux Toolkit's dev checks will warn.

unwrap, condition and cancellation

The promise returned by dispatch(thunk()) has an unwrap() method. It returns the payload, or throws the error payload, so components can use ordinary try/catch or toast an error:

JavaScript
// Real Redux Toolkit code (read-only), inside an event handler
try {
  const user = await dispatch(createUser(form)).unwrap();
  navigate(`/users/${user.id}`);
} catch (err) {
  setFormErrors(err);   // the rejectWithValue payload, or a serialized error
}

Other options on the third argument of createAsyncThunk:

  • condition(arg, { getState }): return false to skip the call entirely, for example condition: (_, { getState }) => getState().todos.status !== 'loading' to prevent double fetching. A skipped thunk dispatches nothing (unless dispatchConditionRejection: true).
  • signal: an AbortSignal on thunkApi. Pass it to fetch. The promise returned by dispatch has .abort(), which cancels the request and dispatches rejected with meta.aborted === true.
  • getPendingMeta and idGenerator customize metadata and ids.

Use a condition rather than checking state in every component. It keeps the rule in one place next to the request.

Where should the status live?

For one request per slice, status and error fields on the slice are fine. When many requests share a slice (per-user, per-page), track status per key or switch to RTK Query, which stores status, data and errors per cache entry for you. See RTK Query basics.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What action types does createAsyncThunk('posts/load', fn) generate?

    The prefix is combined with pending, fulfilled and rejected.
  2. 2. Why does a slice use extraReducers for thunk actions?

    extraReducers responds to actions defined elsewhere, including generated thunk actions.
  3. 3. What does unwrap() do on the promise returned by dispatch(thunk())?

    It lets you use try/catch around a dispatch.
  4. 4. How can you prevent a thunk from starting when a request is already running?

    condition runs first and can return false to skip the call.

Summary

  • createAsyncThunk(prefix, payloadCreator) generates pending, fulfilled and rejected actions.
  • Handle them in extraReducers with the builder callback.
  • Use rejectWithValue for server error bodies, unwrap() for try/catch, condition to skip, signal to cancel.
  • meta.requestId helps ignore stale responses.
  • For caching and many requests, move to RTK Query.

Next: RTK Query basics