T
TanStack•11mo ago
old-apricot

How to update component B when the useQuery within component A finishes successfully?

I have a component A in the main part of my app which makes a call using useQuery, on successful completion I would like this data to also show up inside component B. Note that component B is not a child or sibling component, it live in another place, being show in a sidebar. I am not sure how I should do this. In the past the onSuccess callback could be used to maybe persist in a state manager and share the data in such a way. I could do the same using a useEffect but I just want to check before I act 😉 Thx in advance. It's important for component B to change whenever the data changes.
11 Replies
passive-yellow
passive-yellow•11mo ago
useQuery in both components, in component B, u can use select function, to subscribe to smaller set of data... or tryi using queryClient.ensureQueryData
old-apricot
old-apricotOP•11mo ago
But wouldn't this mean that component B would also make the call (I know the get deduplicated). Also important to know, only component A has sufficient data to actually make the API call, component B has no idea.
passive-yellow
passive-yellow•11mo ago
U can use the enabled flag for conditional quering... or use queryClient.getQueryData....
old-apricot
old-apricotOP•11mo ago
I assume getQueryData is a one time thing? Or does it cause a rerender on update?
old-apricot
old-apricotOP•11mo ago
I did see https://tanstack.com/query/latest/docs/reference/QueryObserver would this be what I am looking for?
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
From An unknown user
From An unknown user
eastern-cyan
eastern-cyan•11mo ago
Component B must use the useQuery to subscribe to any cache changes. if you don't want component B to initiate a fetch utilise enabled: false as a parameter on Component B's useQuery
old-apricot
old-apricotOP•11mo ago
@wleistra ah even with enabled false it will react to changes from fetches from compoment A?
constant-blue
constant-blue•11mo ago
yes
old-apricot
old-apricotOP•11mo ago
cool!
constant-blue
constant-blue•11mo ago
also, set a staleTime: Infinity (and maybe gcTime: Infinity) in component B so the data does not expire while component B is subscribed, even if component A gets unmounted
old-apricot
old-apricotOP•11mo ago
ah good idea! thanks for the help guys they will always show together

Did you find this page helpful?