React Query useInfiniteQuery invalidate individual items

Viewed 1637

How can I invalidate a single item when working with useInfiniteQuery? Here is an example that demonstrates what I am trying to accomplish.

Let`s say I have a list of members and each member has a follow button. When I press on to follow button, there is a separate call to the server to mark that the given user is following another user. After this, I have to invalidate the entire infinite query to reflect the state of following for a single member. That means I might have a lot of users loaded in infinite query and I need to re-fetch all the items that were already loaded just to reflect the change for one item.

I know I can change the value in queryClient.setQueryData when follow fetch returns success but without following this with invalidation and fetch of a member, I am basically going out of sync with the server and relying on local data.

Any possible ways to address this issue?

Here is a reference UI photo just in case if it will be helpful.

enter image description here

1 Answers

I think it is not currently possible because react-query has no normalized caching and no underlying schema. So one entry in a list (doesn't matter if it's infinite or not) does not correspond to a detail query in any way.

If you prefix the query-keys with the same string, you can utilize the partial query key matching to invalidate in one go:

['users', 'all']
['users', 1]
['users', 2]

queryClient.invalidateQueries(['users]) will invalidate all three queries.

But yes, it will refetch the whole list, and if you don't want to manually set with setQueryData, I don't see any other way currently.

If you return the whole detail data for one user from your mutation, I don't see why setting it with setQueryData would get you out-of-sync with the backend though. We are doing this a lot :)

Related