Blog>
Snippets

Parameterizing createAsyncThunk Calls

Show how to pass arguments to createAsyncThunk actions to perform dynamic API requests, such as fetching a user profile by ID.
import { createAsyncThunk } from '@reduxjs/toolkit';
import { userAPI } from './userAPI';

// Define the 'fetchUserProfile' async thunk
export const fetchUserProfile = createAsyncThunk(
  'users/fetchProfile',
  // The payload creator receives the 'userId' argument.
  async (userId, { rejectWithValue }) => {
    try {
      // Make an API call to fetch the user profile.
      const response = await userAPI.fetchById(userId);
      return response.data; // Resolve the promise with the data
    } catch (error) {
      // Use `rejectWithValue` to return a custom error payload
      return rejectWithValue(error.response.data);
    }
  }
);
This snippet defines a createAsyncThunk called 'fetchUserProfile', which takes a user ID as an argument and makes an API call to fetch that user's profile data. If the request is successful, it resolves with the fetched data. If it fails, it uses 'rejectWithValue' to pass a custom error payload.
// Dispatch the 'fetchUserProfile' thunk with a specific user ID
// This would be done inside a component or other part of the application
import { fetchUserProfile } from './userThunks';

// Dispatch the thunk with a user ID
// The 'userId' is passed as an argument when dispatching
dispatch(fetchUserProfile(123));
This snippet shows how to dispatch the previously defined 'fetchUserProfile' thunk with a specific user ID. It imports the thunk and dispatches it with the user ID as an argument.