Blog>
Snippets

Customizing createAsyncThunk with Transform Functions

Provide an example of how to use `transformResponse` to preprocess API data before it reaches the reducer when using createAsyncThunk.
import { createAsyncThunk } from '@reduxjs/toolkit';

// Define the transform function
const transformResponse = (response) => {
  // Assume response is an object with a data property,
  // transform it as needed before returning
  const transformedData = response.data.map(item => ({ ...item, transformed: true }));
  return transformedData;
};

// Use createAsyncThunk with transformResponse
export const fetchCustomData = createAsyncThunk(
  'data/fetchCustom',
  async (arg, { getState, requestId, signal }) => {
    const response = await fetchSomeData(arg, signal);
    // Preprocess the API data using the transform function before sending it to the reducer
    return transformResponse(response);
  }
);
This code defines a transform function called `transformResponse` which preprocesses the API data. It then uses this function within `createAsyncThunk` to transform the data before it reaches the reducer. This way, data normalization or any other preprocessing is handled right after the API call succeeds and before the data is stored in the Redux state.