Lesson 7 of 16

Async Logic and Data Fetching with createAsyncThunk

Explains how Redux Toolkit createAsyncThunk standardizes asynchronous logic by generating predictable pending fulfilled and rejected actions, integrating async workflows cleanly into slices while keeping reducers pure and reducing boilerplate.

Context / Motivation

In the real world, applications rarely work with static data. They need to fetch data from APIs, post updates, and handle success or failure gracefully.

In traditional Redux, this meant:

  1. Writing three separate action types: FETCH_START, FETCH_SUCCESS, FETCH_FAILURE
  2. Writing three corresponding action creators.
  3. Writing reducer cases for each.
  4. Manually dispatching actions before and after async calls.

It worked, but it was verbose and error-prone — a classic example of Redux boilerplate fatigue.

Redux Toolkit’s createAsyncThunk() solves this problem. It provides a structured, declarative way to handle asynchronous logic—one that integrates seamlessly with your slices.


Conceptual Explanation

1. The Core Idea

A thunk is just a function that delays work. In Redux, a “thunk action” is a function that can perform side effects and then dispatch actions.

Traditionally, you might write:

function fetchUsers() {
  return async function (dispatch) {
    dispatch({ type: "FETCH_USERS_START" });
    try {
      const res = await fetch("/api/users");
      const data = await res.json();
      dispatch({ type: "FETCH_USERS_SUCCESS", payload: data });
    } catch (err) {
      dispatch({ type: "FETCH_USERS_FAILURE", error: err.message });
    }
  };
}

createAsyncThunk() automates this pattern.

You define a single thunk, and it automatically dispatches three lifecycle actions:

  • pending
  • fulfilled
  • rejected

2. Using createAsyncThunk()

Here’s a basic example:

import { createAsyncThunk } from "@reduxjs/toolkit";
 
export const fetchUsers = createAsyncThunk(
  "users/fetchUsers", // action type prefix
  async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    return response.json(); // becomes action.payload
  }
);

That’s it. This generates three action types automatically:

users/fetchUsers/pending
users/fetchUsers/fulfilled
users/fetchUsers/rejected

You can then handle those in your slice’s extraReducers.


3. Handling Async States in the Slice

Let’s create a slice that reacts to those lifecycle events.

import { createSlice } from "@reduxjs/toolkit";
import { fetchUsers } from "./thunks";
 
const usersSlice = createSlice({
  name: "users",
  initialState: {
    data: [],
    status: "idle", // 'idle' | 'loading' | 'succeeded' | 'failed'
    error: null,
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchUsers.pending, (state) => {
        state.status = "loading";
      })
      .addCase(fetchUsers.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.data = action.payload;
      })
      .addCase(fetchUsers.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.error.message;
      });
  },
});

Key insight: Reducers inside extraReducers handle actions not defined in the reducers field — perfect for async thunks, since those actions are auto-generated elsewhere.


4. Using It in React

Now, in your React component:

import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { fetchUsers } from "./usersSlice";
 
function UsersList() {
  const dispatch = useDispatch();
  const { data, status, error } = useSelector((state) => state.users);
 
  useEffect(() => {
    if (status === "idle") {
      dispatch(fetchUsers());
    }
  }, [status, dispatch]);
 
  if (status === "loading") return <p>Loading...</p>;
  if (status === "failed") return <p>Error: {error}</p>;
 
  return (
    <ul>
      {data.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

RTK automatically tracks the async lifecycle. Your reducer reacts to each stage, updating status and data accordingly.


5. Passing Arguments to Thunks

You can pass arguments when dispatching a thunk:

export const fetchUserById = createAsyncThunk(
  "users/fetchById",
  async (userId) => {
    const response = await fetch(`/api/users/${userId}`);
    return response.json();
  }
);

Usage:

dispatch(fetchUserById(42));

The 42 becomes the argument to your async callback.


6. Handling Errors and Rejections

If the promise rejects or an error is thrown, RTK automatically dispatches the rejected action.

You can also manually reject with a custom message using rejectWithValue:

export const fetchUserSafe = createAsyncThunk(
  "users/fetchSafe",
  async (userId, { rejectWithValue }) => {
    const response = await fetch(`/api/users/${userId}`);
    if (!response.ok) {
      return rejectWithValue("User not found");
    }
    return response.json();
  }
);

Then handle it in your slice’s reducer:

.addCase(fetchUserSafe.rejected, (state, action) => {
  state.error = action.payload || action.error.message;
});

This gives you full control over error messaging and recovery.


Real-World Illustration

Let’s apply this to an e-commerce app:

  • When the user opens the page, you fetch products from the backend.
  • While loading, you show a spinner.
  • If the request fails, display a user-friendly message.
  • Once loaded, display the products.

Without RTK, this would take 60–70 lines across multiple files. With createAsyncThunk(), you can implement the same flow in fewer than 20 lines of clear, declarative logic — with standardized async states.

This consistency scales beautifully when you have 10+ async calls (e.g., fetching products, updating carts, posting orders, etc.).


Evolution / Refinement

Before createAsyncThunk, async flows were handled through ad hoc thunks or sagas — both powerful but verbose.

RTK’s approach has three refinements:

  1. Convention over configuration: you don’t manually define start/success/failure actions.
  2. Consistency: every async thunk emits the same predictable lifecycle events.
  3. Integration: async actions plug directly into slices — no extra wiring.

As apps grow, this structure allows teams to treat async behavior as first-class state logic, not side noise.


Principle / Takeaway

createAsyncThunk() brings structure, simplicity, and safety to async Redux code.

It lets you:

  • Write asynchronous code declaratively.
  • Track loading and error states automatically.
  • Keep reducers pure and focused.
  • Avoid duplicated boilerplate for every network request.

In essence, it makes side effects predictable — extending Redux’s philosophy of deterministic data flow to the async domain.


✅ Next Lesson Preview – Lesson 8: Configuring and Using configureStore() In the next lesson, we’ll explore how Redux Toolkit simplifies store setup with configureStore(), how it automatically includes middleware (like thunk), enables DevTools, and organizes multiple slices into one cohesive store.