Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Query useInfiniteQuery invalidate individual items

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

like image 804
Saik Avatar asked Feb 26 '21 16:02

Saik


People also ask

How do you Refetch a react query?

Using auto refetching in React Query To use the auto refetch mode, you can pass an optional parameter to the React Query hook called refetchInterval . The value is in milliseconds. const { isLoading, data } = useQuery( 'vehicle', async () => { const { data } = await axios.

What is stale in react query?

StaleTime: The duration until a query transitions from fresh to stale. As long as the query is fresh, data will always be read from the cache only - no network request will happen!

What is useInfiniteQuery?

Use useInfiniteQuery instead of useQuery , if you want to show large data gradually more. For instance, you have many numbered pages, and you want to show the first ten pages initially. After clicking on Show more pages , the user should see three pages more than before.


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

like image 101
TkDodo Avatar answered Nov 15 '22 21:11

TkDodo