Blog>
Snippets

Creating a Redux Slice using createAsyncThunk

Showcase how to create a slice for user data with async requests using the createAsyncThunk API to fetch data from an external API.
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';

export const fetchUserData = createAsyncThunk(
  'user/fetchUserData',
  async (userId, thunkAPI) => {
    const response = await axios.get(`https://api.example.com/users/${userId}`);
    return response.data;
  }
);
Defines an async thunk action for fetching user data from an external API using the createAsyncThunk API of Redux Toolkit.
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 = action.payload;
        state.loading = 'idle';
      })
      .addCase(fetchUserData.rejected, (state, action) => {
        state.loading = 'idle';
        state.error = action.error.message;
      });
  }
});

export const { actions, reducer } = userSlice;
Creates a Redux slice named 'user' with an initial state and uses the async thunk action previously defined to populate the state upon completion. It also manages loading and error states.
import { configureStore } from '@reduxjs/toolkit';
import { reducer as userReducer } from './userSlice';

export const store = configureStore({
  reducer: {
    user: userReducer
  }
});
Configures the Redux store with the 'user' slice reducer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redux Async Thunk Example</title>
</head>
<body>
<div id="app"></div>
<script src="path-to-your-compiled-js-file.js"></script>
</body>
</html>
The HTML document that includes a div with the id 'app' where the React application will mount, and a script tag to include the compiled JavaScript file that contains the Redux store and logic.