T
TanStack3y ago
deep-jade

read, mutate, refetch the same query key in 2 components

so I have Component A that uses useQuery to fetch data, and I put it in a key named data. Now I have component B, my strategy would be to use queryClient to read /display the query data so I don't need to do useQuery again, then useMutation to update it. Is this the correct way to do things? Should I just add this is the useMutation in Component B
onSuccess: async () => {
await queryClient.refetchQueries({ queryKey: ['data'] })
},
onSuccess: async () => {
await queryClient.refetchQueries({ queryKey: ['data'] })
},
and I can expect after I click on Send button, the mutation is done and new data shall be fetched and displayed?
4 Replies
other-emerald
other-emerald3y ago
If you need to read the data in component B you can just use useQuery again with the same key and it will read from the cache. For updating the data after the mutation you can call queryClient.invalidateQueries inside onSuccess as shown here: https://tanstack.com/query/v4/docs/react/guides/invalidations-from-mutations. The new data will be fetched and displayed where useQuery is used.
Overview | TanStack Query Docs
React Query is often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your React applications a breeze. Motivation
deep-jade
deep-jadeOP3y ago
oh, in that case what's the difference between I read the data from queryClient and useQuery in componentB? I thought using useQuery in Component B in this case might cause unnecessary fetch?
other-emerald
other-emerald3y ago
useQuery will read from the cache if it's available or fetch the data if it's not in the cache. queryClient only reads from the cache, so if the data is not already cached it'll return nothing (and nothing will be displayed in your component). Also useQuery is declarative. You call it in your component and if the cache changes, it will rerender your component with the new data. Whereas reading the data using query client is imperative, you'd have to call it manually when you want the updated data and it won't trigger your component to re-render when the cache changes. To get data to display inside a component, useQuery is preferred. Using the queryClient is for advanced cache manipulations (for optimistic updates for example).
deep-jade
deep-jadeOP3y ago
Jaha... I see. So originally I was writing like that and it was actually the "correct" way of doing things. Thanks!

Did you find this page helpful?