Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing cached data in RTK Query(new)

Imagine we have 3 component. first is index which is parent. second is filter component and third one is table component. I used mutations for filter some data and show them in table. In filter component I did this:

  const [filterSomeData] = useFilterSomeDataMutation();
  const data = filterSomeData(myFilter);

Now I need to access data in table component. Redux toolkit query with every request cache the result , how can I access that?

like image 578
Maverick0o0 Avatar asked Sep 14 '25 12:09

Maverick0o0


2 Answers

Generally: If you are receiving data from the server without triggering a change on the server, you should be using a query, not a mutation. Yes, you can do POST requests with Queries and the syntax is 100% the same as with mutations.

Then you should be using that useQuery hook in all components that need that data, with the same argument as you passed in initially. That means if you have something like a filter, that you should either pass that filter in by props (by lifting the filter state up to a common parent) or keeping that filter in a Redux slice and getting it from Redux before calling your query hook.

Since you are calling that useQuery hook with the same argument in multiple components, it will not make multiple requests, but reuse the response of the first request.

like image 86
phry Avatar answered Sep 17 '25 01:09

phry


As in RTK documentation is explained, the proposed solution is calling useQuery hooks with the same arguments as before it called. It retrieves data from cached enpoints, But as I need too many arguments to send to query hook, and I should send it to other component, so I prefer to use the store object to access data from endpoints as below:

    const store = useStore();
    const cachedQueries = store.getState().dashboardApi.queries;

Then I made an object with endpoint's name as key and their data as value:

    let dashboardResult: { [key: string]: any } = {};        
    Object.values(cachedQueries).forEach((item: any) => {
        dashboardResult = { 
           ...dashboardResult,
           ...{ [item?.endpointName]: item?.data?.data }
        }
    });
like image 32
Mahmonir Bakhtiyari Avatar answered Sep 17 '25 02:09

Mahmonir Bakhtiyari