Async Operations with Redux Toolkit
Learn how to handle API requests, loading states, successful responses, and errors using Redux Toolkit.
1. What Are Asynchronous Operations?
An asynchronous operation is a task that takes time to complete without blocking the rest of the application. Examples include fetching student details from an API, submitting a form, and loading course information from a server.
In a React application, an API request may take several seconds. During that time, the application should be able to show a loading message, display the result when the request succeeds, or show an error when the request fails.
Example: Student Dashboard
When a student opens the dashboard, the application requests student information from an API. Redux Toolkit can manage the request lifecycle and keep the resulting data in the store.
API Request Flow
2. What Is createAsyncThunk()?
createAsyncThunk() is a Redux Toolkit utility used to create action creators for asynchronous operations. It simplifies handling the lifecycle of an operation such as an API request.
For each asynchronous operation, Redux Toolkit generates three lifecycle actions:
Pending
Dispatched when the asynchronous operation starts. The application can set its loading state to true.
fetchStudents.pending
Fulfilled
Dispatched when the operation completes successfully. The application can save the returned data in the store.
fetchStudents.fulfilled
Rejected
Dispatched when the operation fails. The application can save an error message in the store.
fetchStudents.rejected
3. Install Required Packages
If you are starting a new React project, install Redux Toolkit and React-Redux.
npm install @reduxjs/toolkit react-redux
This lesson uses a sample public API to demonstrate fetching data. You can replace the URL with your own student API endpoint.
4. Create an Async Thunk
First, create an asynchronous thunk that requests student data from an API. The example below uses JSONPlaceholder to demonstrate the request lifecycle.
File: studentSlice.js
import {
createSlice,
createAsyncThunk
} from "@reduxjs/toolkit";
export const fetchStudents = createAsyncThunk(
"students/fetchStudents",
async (_, { rejectWithValue }) => {
try {
const response = await fetch(
"https://jsonplace.typicode.com/users"
);
if (!response.ok) {
throw new Error("Failed to fetch students");
}
return await response.json();
} catch (error) {
return rejectWithValue(
error.message || "Something went wrong"
);
}
}
);
Explanation
5. Create the Slice with Loading and Error States
Now define the initial state and handle the pending, fulfilled, and rejected actions inside extraReducers.
File: studentSlice.js (continued)
const studentSlice = createSlice({
name: "students",
initialState: {
data: [],
loading: false,
error: null
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchStudents.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(fetchStudents.fulfilled, (state, action) => {
state.loading = false;
state.data = action.payload;
})
.addCase(fetchStudents.rejected, (state, action) => {
state.loading = false;
state.error =
action.payload || action.error.message;
});
}
});
export default studentSlice.reducer;
Understanding the Initial State
{
data: [],
loading: false,
error: null
}
6. Configure the Redux Store
Register the student reducer in the Redux store so that React components can access the asynchronous request state.
File: store.js
import { configureStore } from "@reduxjs/toolkit";
import studentReducer from "./studentSlice";
export const store = configureStore({
reducer: {
students: studentReducer
}
});
Store Structure
{
students: {
data: [],
loading: false,
error: null
}
}
Because the reducer is registered under the students key, the component can select the data using state.students.data.
7. Fetch and Display Data in React
Use useDispatch() to start the asynchronous request and useSelector() to read the data, loading state, and error message.
File: StudentList.jsx
import { useEffect } from "react";
import {
useDispatch,
useSelector
} from "react-redux";
import { fetchStudents } from "./studentSlice";
function StudentList() {
const dispatch = useDispatch();
const {
data,
loading,
error
} = useSelector((state) => state.students);
useEffect(() => {
dispatch(fetchStudents());
}, [dispatch]);
if (loading) {
return <p>Loading students...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<div>
<h2>Student List</h2>
{data.length === 0 ? (
<p>No students found.</p>
) : (
<ul>
{data.map((student) => (
<li key={student.id}>
{student.name} - {student.email}
</li>
))}
</ul>
)}
</div>
);
}
export default StudentList;
8. Connect the Store to React
Wrap your React application with Provider so StudentList can access the Redux store.
File: main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import { store } from "./store";
import StudentList from "./StudentList";
createRoot(document.getElementById("root")).render(
<StrictMode>
<Provider store={store}>
<StudentList />
</Provider>
</StrictMode>
);
9. Understand the Request Lifecycle
Async Redux Lifecycle
Fulfilled
Save response data
Set loading to false
Rejected
Save error message
Set loading to false
Expected UI States
Loading students...
Student names and email addresses are displayed.
An error message is displayed if the request fails.
10. Handling API Errors Properly
An HTTP error response does not automatically cause fetch() to throw an exception. Check response.ok and throw or return a rejection when the status is unsuccessful.
const response = await fetch("/api/students");
if (!response.ok) {
throw new Error(
`Request failed: ${response.status}`
);
}
const data = await response.json();
For a rejected thunk, custom errors returned through rejectWithValue() are available in action.payload. Other errors may be available through action.error.message.
11. Best Practices
Keep API Logic Organized
Place asynchronous request logic in an appropriate thunk or service layer rather than mixing it into UI rendering.
Handle Every Lifecycle State
Handle pending, fulfilled, and rejected actions so users understand what is happening.
Avoid Unnecessary Requests
Consider whether data is already available before dispatching a new request, especially when components mount repeatedly.
Keep Reducers Predictable
Reducers should update state only. Perform API calls inside thunks or another suitable asynchronous layer.
12. Practice Tasks
Task 1: Fetch Students
Create a fetchStudents thunk that retrieves student records from an API.
Task 2: Handle Loading State
Show a loading message while the request is in progress.
Task 3: Handle Errors
Display a meaningful message when the request fails.
Task 4: Build a Course List
Create a separate async thunk and slice for fetching courses.
Summary
Redux Toolkit supports asynchronous operations through utilities such as createAsyncThunk(). It generates pending, fulfilled, and rejected lifecycle actions that can be handled in a slice using extraReducers. The Redux state can store the returned data, loading status, and error message. React components use useDispatch() to start requests and useSelector() to read the resulting state. This approach helps build predictable API workflows with clear loading, success, and error behavior.