Is it ok to call queryClient.fetchQuery() in a query fn?
I could use select, but let's say I want to reuse a cached value in multiple components in my UX. I think .select would need to run in each component my useQuery appears?
4 Replies
other-emerald•3y ago
Sure is, but can you describe the broader use-case?
fair-roseOP•3y ago
Cool, here's what I'm up to:
1. Loading a large payload (think of it as a search index)
2. Creating a class instanace to manage the large payload (think of it as a local searcher for the index)
The "searcher instance" is used in a few different components across the tree. I'd like to dispose of it when it's not in use at all, but be able to create it when at least one component needs it and share the same instance across components.
tanstack-query seems pretty well suited for this, though I can't serialize the searcher instance. So I was thinking I could have an "inner query" to get the payload (step 1), and then use the outer query to manage the "search instance"
I think the one downside I see is that I'd need to manage two query timeouts (stale, invalidate), but so long as they're set to the same values I think that should work ok?
I think one alternative is to have two queries serially:
useSearcher = () => {
useQuery({... /* search index payload /})
useQuery({... / searcher instance, enabled only if above query succeeds and use data as input */)
}
but potentially there's an assumed relationship between these two queries that feels a bit looser.
Right now I have one query that does both steps, the down side is that none of it could be serialized (say serializing the payload and recreating the searcher instance after hydration)
other-emerald•3y ago
keep in mind that if you do
queryClient.fetchQuery in the second query to get data from the first one, you're not having an active observer, so that data might be garbage collected sooner than you'd expectfair-roseOP•3y ago
ah, that's a good point. thanks!