Search code examples
reactjsnext.jsredux-toolkitrtk-query

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?


Solution

  • 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.