Search code examples
reactjsredux-toolkitrtk-query

RTK useLazyQuery always making calls to the API even when called with same params on multiple components


I am trying to make a request use the cached data from another component when doing a lazy query. The parent component (not direct parent, so I don't want to drill down a large data set through props) makes a lazy query through RTK like so:

const [getDocuments, { data: contractDocuments, isLoading, isFetching }] = useLazyGetContractDocumentsQuery();


// inside a fetch function
  getDocuments({
    prop1,
    prop2,
    prop3,
  });

Then the child component does the same

getDocuments({
  prop1,
  prop2,
  prop3,
}).unwrap().then(documents=>{
  console.log(documents);         
});

I have verified that the props are the same, the data returned is the same, but in both cases every time it is called in either component it hits the API endpoint to get the data. It never gets it from cache.

The documentation seems to say that the lazy queries are different than regular useQuery by the fact that you choose when to call. See the Feature Comparison of the different hooks. But I have not been able to use the cache with them. Am I missinterpreting the documentation, missed some exception to the caching rule or there is the chance that in another place I am disabling caching somehow?

Btw, the query looks like this:

    getContractDocuments: builder.query<
      ContractDocument[],
      {
        prop1: string;
        prop2: string | null;
        prop3: string;
      }
    >({
      query: body => ({
        url: '/GetDocuments',
        body,
        method: 'POST',
      }),
      transformResponse: (response: ContractDocument[]) => {
        return response.map(d => ({
          ...d,
          showIconViewFileInNewWindows: extensions.has(`${d.type}`),
        }));
      },
    }),

Solution

  • By default the lazy query trigger always make a request call, however you can provide a second argument as true to use cache when available

    getDocuments({
      prop1,
      prop2,
      prop3,
    }, true)
    

    See docs (UseLazyQueryTrigger)