T
TanStack•14mo ago
ratty-blush

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
fair-rose
fair-rose•14mo 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
ratty-blush
ratty-blushOP•14mo 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.
fair-rose
fair-rose•14mo ago
U can use the enabled flag for conditional quering... or use queryClient.getQueryData....
ratty-blush
ratty-blushOP•14mo ago
I assume getQueryData is a one time thing? Or does it cause a rerender on update?
ratty-blush
ratty-blushOP•14mo 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
eager-peach
eager-peach•14mo 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
ratty-blush
ratty-blushOP•14mo ago
@wleistra ah even with enabled false it will react to changes from fetches from compoment A?
fair-rose
fair-rose•14mo ago
yes
ratty-blush
ratty-blushOP•14mo ago
cool!
fair-rose
fair-rose•14mo 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
ratty-blush
ratty-blushOP•14mo ago
ah good idea! thanks for the help guys they will always show together

Did you find this page helpful?