Blog>
Snippets

Caching Responses in createAsyncThunk

Demonstrate how to implement a caching mechanism within createAsyncThunk to avoid unnecessary network requests.
import { createAsyncThunk } from '@reduxjs/toolkit';

// An in-memory cache to store responses
const cache = {};

// createAsyncThunk with caching logic
export const fetchWithCache = createAsyncThunk(
  'fetchWithCache',
  async (arg, { getState, requestId }) => {
    const cacheKey = JSON.stringify(arg);
    const currentRequestId = getState().currentRequestId;
    // If there is a cached value and the request is not currently pending,
    // return the cached value
    if (cache[cacheKey] && currentRequestId === requestId) {
      return cache[cacheKey];
    }
    // Otherwise, perform the actual API request
    const response = await fetch(arg.url);
    const data = await response.json();
    // Cache the new response for future use
    cache[cacheKey] = data;
    return data;
  }
);
This code creates an async thunk called 'fetchWithCache' that uses an in-memory cache object to store API responses. When a request is made, it first checks if the response for the given arguments is already cached and if there's no other request with the same ID already pending to avoid redundant API calls. If a cached response is found, it is returned immediately; otherwise, it proceeds to fetch the data from the server, caches the response, and then returns it.