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?
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.
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 }
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With