Conditional Data Fetching with createAsyncThunk

Illustrate how to perform conditional data fetching based on the current state within a createAsyncThunk action creator.
import { createAsyncThunk } from '@reduxjs/toolkit';

// Define an async thunk action creator
export const fetchUserData = createAsyncThunk(
  async (userId, { getState, rejectWithValue }) => {
    // Access current state to make conditional logic
    const { userData } = getState();

    // Check if user data is already fetched
    if (userData[userId]) {
      // User data is already available, no need to fetch, just return the current data
      return userData[userId];

    try {
      // Fetch the user data from an API
      const response = await fetch(`${userId}`);

      // Check if the response is successful
      if (!response.ok) {
        throw new Error('Network response was not ok');

      // Parse the response data
      const data = await response.json();
      // Return the fetched data
      return data;
    } catch (error) {
      // In case of an error, use rejectWithValue to return a custom error payload
      return rejectWithValue(error.message);
This code defines an async thunk action creator using Redux Toolkit's createAsyncThunk. It conditionally fetches user data from an API only if it hasn't been fetched already, by checking the current state before making an API call. It returns existing data if already present, otherwise it makes the fetch call. It also demonstrates error handling using rejectWithValue.