12

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 Answer 1

1

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 :)

Sign up to request clarification or add additional context in comments.

5 Comments

We have this issue now @TkDodo is there a way to do this today in version 4?
do what exactly?
well lets say we have an infitite query and a list that renders rows with items. Each item has a like button but that button calls another api to set a state in a different relational table. let say we have /api/tweet for the paged data and /api/tweet/[id]/toggleLike. What we are struggeling with is how to optimisticly update that one item in the list..
oh and this might be poor design in the api. But each tweet returns a calculated value for if you have liked it or not. IE tweet {msg: string, like: bool (appended in api from relational data and cant be updated with a put to /tweet/[id].)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.