Async Thunks with createAsyncThunk
Fetch data from an API inside a createAsyncThunk, handle the pending/fulfilled/rejected lifecycle in the slice's extraReducers, and display async status in the UI.
Why Do We Need Async Thunks?
Redux reducers must be pure synchronous functions — they cannot make API calls or run async code. To fetch data from a server and store the result in Redux, we need an async thunk: a function that dispatches plain actions before and after an async operation. Redux Toolkit's createAsyncThunk handles this pattern with minimal boilerplate.
Creating an Async Thunk
createAsyncThunk accepts two arguments: a string action type prefix and a payload creator function that performs the async work and returns the result. It automatically dispatches pending, fulfilled, or rejected actions based on whether the payload creator's promise resolves or rejects.
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
export const fetchPosts = createAsyncThunk(
'posts/fetchPosts', // action type prefix
async (page: number) => { // payload creator
const response = await axios.get('https://api.example.com/posts?page=' + page);
return response.data; // this becomes action.payload
}
);All lessons in this course
- Setting Up the Redux Store and Provider
- Creating Slices with createSlice
- Reading State with useSelector
- Async Thunks with createAsyncThunk