Course contentsShow
← React
Lesson 1734 of 2,39641. State Management EcosystemFree lesson

Async Logic with createAsyncThunk

Handling async operations like API calls with thunks that automatically dispatch pending/fulfilled/rejected actions.

Async Logic with createAsyncThunk

What you'll learn: How Redux Toolkit's createAsyncThunk handles API calls and automatically dispatches actions for loading, success, and error states.

The Promise Lifecycle Problem

When you fetch data from an API, you need to track three states: "loading," "success," and "error." Without a helper, you'd manually dispatch actions for each phase. Redux Toolkit's createAsyncThunk automates this entire workflow.

How createAsyncThunk Works

You define a thunk by providing a name and an async function. Redux Toolkit automatically generates three action types (pending, fulfilled, rejected) and dispatches them as your promise progresses:

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

// Define the async operation
export const fetchUser = createAsyncThunk(
  'users/fetchUser', // action type prefix
  async (userId) => {
    const response = await fetch(`/api/users/${userId}`);
    return response.json(); // This becomes the "fulfilled" payload
  }
);

Handling the Actions in Your Slice

In your slice's extraReducers, handle the auto-generated actions:

const usersSlice = createSlice({
  name: 'users',
  initialState: { data: null, status: 'idle', error: null },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchUser.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchUser.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.data = action.payload;
      })
      .addCase(fetchUser.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      });
  },
});

You dispatch it like any action: dispatch(fetchUser(123)).

Key Takeaway: createAsyncThunk transforms async functions into thunks that automatically dispatch pending, fulfilled, and rejected actions, eliminating boilerplate and making API call state management predictable and consistent.