Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Advanced

createAsyncThunk()

Definition

An RTK API that abstracts the standard Thunk pattern. It accepts a string action type and a payload creator callback that returns a promise, and automatically generates `pending`, `fulfilled`, and `rejected` action types.

Explain Like I'm New

Writing manual thunks (like the previous example) requires typing out 'loading', 'success', and 'error' actions over and over again. `createAsyncThunk` does all of that for you automatically. You just give it the `fetch` call, and it handles the rest.

Real World Example

Fetching a list of movies. You use `createAsyncThunk`, and RTK automatically creates three actions: `fetchMovies/pending`, `fetchMovies/fulfilled`, and `fetchMovies/rejected`.

Common Use Cases

  • •Standardizing API calls in modern Redux apps

Interactive Example

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

// 1. Create the Thunk
export const fetchUsers = createAsyncThunk(
  'users/fetchUsers',
  async () => {
    const response = await fetch('/api/users');
    return response.json(); // This becomes the 'payload' on success
  }
);

// 2. Handle it in the Slice
const usersSlice = createSlice({
  name: 'users',
  initialState: { data: [], status: 'idle' },
  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) => {
        state.status = 'failed';
      });
  }
});

Interview Questions

basic

  • Which RTK function creates async thunks automatically?

intermediate

  • Where inside `createSlice` do you listen for the actions generated by `createAsyncThunk`?

Flash Cards

Question

Which function?

Click to reveal answer
Answer

`createAsyncThunk`.

Question

Where to listen?

Click to reveal answer
Answer

In the `extraReducers` property of the slice. Because the Thunk is created OUTSIDE of the slice, the slice must use `extraReducers` to catch it.