Blog>
Snippets

Using createAsyncThunk with Redux Toolkit 2.0

Provide an example of how to define an async thunk with the createAsyncThunk utility in Redux Toolkit 2.0, including error handling and dispatching.
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

// Define an async thunk that makes an API call
export const fetchUserData = createAsyncThunk(
  'users/fetchByIdStatus', // action type
  async (userId, { rejectWithValue }) => {
    try {
      const response = await fetch(`https://reqres.in/api/users/${userId}`);
      if (!response.ok) {
        throw new Error('Server Error!');
      }
      const data = await response.json();
      return data.data;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);
This JavaScript code defines an async thunk using 'createAsyncThunk' from Redux Toolkit. The thunk 'fetchUserData' make an API call to fetch user data by ID and handles any errors that may occur during the fetch.
const userSlice = createSlice({
  name: 'user',
  initialState: {
    entities: [],
    loading: 'idle',
    error: null
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchUserData.pending, (state) => {
        state.loading = 'pending';
      })
      .addCase(fetchUserData.fulfilled, (state, action) => {
        state.entities.push(action.payload);
        state.loading = 'idle';
      })
      .addCase(fetchUserData.rejected, (state, action) => {
        state.error = action.payload;
        state.loading = 'idle';
      });
  },
});

export const userReducer = userSlice.reducer;
This JavaScript code creates a slice for user data using 'createSlice' from Redux Toolkit that includes the async thunk 'fetchUserData'. It handles updating the state for pending, fulfilled, and rejected cases from the async thunk.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redux Toolkit Example</title>
</head>
<body>
<div id="app"></div>
<script src="path-to-your-entry-point.js"></script>
</body>
</html>
This is the HTML template to host the JavaScript code. The script tag should reference the compiled JavaScript file that includes the Redux Toolkit store and the async thunk.
body {
  font-family: 'Arial', sans-serif;
}

#app {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
This CSS provides basic styling for the HTML template. The '#app' container is centered vertically and horizontally on the page.