reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.54k stars 1.14k forks source link

Am I missunderstanding RTK Query Cache feature? #4454

Open atalayio opened 3 weeks ago

atalayio commented 3 weeks ago

When I make a request in Lazy Query, I cache the returned result and try to use the data in the cache even if the page changes. I make a request, the result is returned, and when I change the page, it appears as data: undefined, even though I set the preferCacheValu to true. What am I doing wrong? My code is given below;

  const [
    getCachedStockDocumentList,
    { data: stockDocumentListData}
  ] = mrpApi.endpoints.getApiStockDocumentStockDocumentList.useLazyQuery();

  console.log(stockDocumentListData)

//request
onClick={async () => await getCachedStockDocumentList({}, true)}
valedobrandi commented 1 week ago

It took me some time to understand, but I believe you should call the hook directly in the other component or pass it as a prop.

const { data, error, isLoading } = useMrpApiQuery()

In this case, it will theoretically recover directly from the cache without making a new request. Adding { skip: false } will prevent the automatic request. Theoretically I believe that it makes more sense to create a state to turn skip on and off. Which in your case makes more sense.

https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching

atalayio commented 1 week ago

It took me some time to understand, but I believe you should call the hook directly in the other component or pass it as a prop.

const { data, error, isLoading } = useMrpApiQuery()

In this case, it will theoretically recover directly from the cache without making a new request. Adding { skip: false } will prevent the automatic request. Theoretically I believe that it makes more sense to create a state to turn skip on and off. Which in your case makes more sense.

https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching

in my page that request not fetching automaticlly. I'm using button for fetching, when I press that button I call that request and when request response success I need the cached response, so when I change page and comeback I can see cached data but it's not, it is undefined and what I wonder am I understand wrong cache feature or is this way wrong?