Blog>
Snippets

Customizing API Requests with serializeQueryArgs

Provide an example of how to use `serializeQueryArgs` to customize query string serialization for complicated queries, such as nested object parameters or arrays, ensuring stable cache keys.
import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react';

const complexApi = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  endpoints: (builder) => ({
    getComplexData: builder.query({
      query: ({ params }) => ({ url: `complexEndpoint`, method: 'GET', params }),
      serializeQueryArgs: ({
        endpointName,
        queryArgs: { params },
        endpointDefinition
      }) => {
        // Serialize the nested params object into a stable string
        const serializedParams = JSON.stringify(
          Object.keys(params)
            .sort()
            .reduce((acc, key) => {
              acc[key] = params[key];
              return acc;
            }, {})
        );
        // Use the default serializer for the rest
        return defaultSerializeQueryArgs({
          endpointName,
          queryArgs: { serializedParams },
          endpointDefinition
        });
      }
    })
  })
});
This code creates an API service with Redux Toolkit Query that includes a 'getComplexData' endpoint. The `serializeQueryArgs` function is overridden to handle the serialization of query arguments that include a nested 'params' object. It serializes the nested object into a stable string by sorting the keys and then using JSON.stringify. It then calls the default serializer with this new serializedParams object to ensure a stable cache key.