Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RTK Query: How store data into specific state path while ignoring dynamic parameter

Right now, I'm using Redux Toolkit Query to fetch data from API. But that API required a new signature in the query parameter every time we send a request. As in the code below:

export const restApi = createApi({
  reducerPath: "restApi",
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/pokemon/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query({
      query: ({ name, signature }) => `${name}?signature=${signature}`
    }),
  }),
});

Which redux will save it in a different state path as below image enter image description here

My question is, how do I make rtk-query ignore the signature parameter and just update the state of the request with the same name?

like image 325
Expl0de Avatar asked Oct 16 '25 02:10

Expl0de


1 Answers

There is available on the query endpoints a serializeQueryArgs property that allows for providing "a custom cache key value based on the query arguments". This seems to be exactly what you are asking for.

Example:

export const restApi = createApi({
  reducerPath: "restApi",
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/pokemon/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query({
      query: ({ name, signature }) => `${name}?signature=${signature}`,
      serializeQueryArgs: ({ queryArgs }) => {
        const { name } = queryArgs;
        return { name }; // omit `signature` from the cache key
      },
    }),
  }),
});
like image 147
Drew Reese Avatar answered Oct 17 '25 14:10

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!