Search code examples
redux-toolkitrtk-query

RTK Query customize and ignore specific query params used to cache requests


I have an api i do not control

I want to only use some of the query params in the RTK document store to cache requests.

For example when calling the generated hook

const {data, error, isLoading} = useReqQuery({ 
  param1: val1, 
  param2: val2, 
  param3: val3, 
  param4: val4
})

I want to only cache requests when param1 and param2 are different and not param3 or param4.

I have looked at the docs and found cache lifecycle functions but not seeing if there are ways to ignore specific query params


Solution

  • We can customize how requests are cached using the serializeQueryArgs option in createApi

    // apiSlice.ts
    getEntities: builder.query({
        query: ({ param1, param2, param3, param4 }) => ({
          url: entityEndpoint,
          method: 'POST',
        }),
        serializeQueryArgs: ({ queryArgs }) => {
          const { param1, param2 } = queryArgs;
          // omits `param3`, and `param4` from the cache key
          return { param1, param2 }; 
        },