Search code examples
redux-toolkitrtk-query

RTK Query manual cache update without known previous query args


How to make optimistic/pessimistic cache update (probably with updateQueryData), but without knowing the arguments of previous queries?

updateQueryData(
  "getItems",
  HERE_ARE_THE_ARGUMENTS_I_DONT_HAVE,
  (data) => {
     ...
  }
)

For example:

  • getPosts query with args search: number
  • updatePosts mutation

Example actions:

  1. Go to the table, first request getPosts with search = "" is cached.
  2. Write in search input abc.
  3. Second request getPosts with search = "abc" is cached.
  4. I update one element within the table with pessimistic update - successfully modifying cache of second request (previous step)
  5. Clear search input
  6. Table shows the same state from first step, even if one element should be modified

But I need universal solution. I don't know how many different cached entries will be there. And also my case is more complex, because I have other args than "search" to worry about (pagination).

Possible solutions??

  1. It would be perfect if there's a method to access all previous cached queries, so I could go with updateQueryData for each of them, but I cannot find simple way to do that.
  2. I thought about accessing getState() within onQueryStarted and retrieving query parameters from there (in order to do above), but it's not elegant way
  3. I thought about looking for a way to invalidate previous requests without invalidating the last request, but also cannot find it

Solution

  • Okay, I found solution here Is it possible to optimistically update all caches of a endpoint?

    Using api.util.selectInvalidatedBy(getState(), { type, id }) gives you in return list of cached queries with endpointNames and queryArgs. Then you can easily mutate these caches by updateQueryData.

    There's also new problem created here, which is situation where modifying some particular properties may change response from API in unpredictable way. For example in a list you may sort by status, which you can modify. Then changing the cache would be bad idea and instead of that I've created new tag which is invalidated with each update { type: "getItems", id: "status" } and for getItems it would be like { type: "getItems", id: sortBy }