Blog>
Snippets

Basic createAsyncThunk Usage

Demonstrate the setup of createAsyncThunk to perform a simple GET request to an API endpoint and handle the fulfilled action in the reducer to store the fetched data.
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

// Define the createAsyncThunk function
export const fetchUserData = createAsyncThunk(
  'user/fetchUserData',
  async (userId, thunkAPI) => {
    const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
    const data = await response.json();
    return data;
  }
);
This code snippet defines an asynchronous thunk using createAsyncThunk from Redux Toolkit to fetch user data based on a user ID from a placeholder API.
import { createSlice } from '@reduxjs/toolkit';
import { fetchUserData } from './pathToFetchUserData';

// Define the slice with the async thunk
const userSlice = createSlice({
  name: 'user',
  initialState: {
    data: null,
    status: 'idle',
  },
  reducers: {},
  extraReducers: {
    [fetchUserData.fulfilled]: (state, action) => {
      state.data = action.payload;
      state.status = 'fulfilled';
    }
    // Handle other actions like pending, rejected here if needed
  }
});

export const userReducer = userSlice.reducer;
This code snippet creates a slice using createSlice from Redux Toolkit which integrates the asynchronous thunk. It updates the state with the fetched data when the fetchUserData action is fulfilled.