I have a component that uses useQuery
from React Query like this:
const { data } = useQuery(
["products", selectedStore],
fetchProductsByStoreId
)
selectedStore
is a local state variable that can be changed from the UI, triggering a request to the API for new products. My problem is, that I also need to use the data from the request in another component, preferably via queryCache.getQueryData
, but to do this, I need to provide a key, that is not only the string "Products"
but the whole array ["products", selectedStore]
.
The other component does not have access to selectedStore
, so my question is, is there a way the other component can access this query data without hoisting selectedStore
to global state? I would like to keep the data in the queryCache
and not hoist it either.
So if you want to retrieve data for a specific key, you need the (full) key. Moving your client state up to the tree to make it accessible to all component that need it, or, if necessary to global client state seems like the best solution.
queryClient.getQueryData
also supports query filters, so you can match on the queryKey with a custom match function if you want. But without knowing what the selectedStore
is, if there are multiple entries in the cache, e.g. ["products", 1]
and ["products", 2]
, how would you know which one to use?
Also note that queryClient.getQueryData
is an imperative operation that doesn't create a subscription - so if the underlying data changes, that component will not be re-rendered. Only useQuery
or a custom subscription (via queryClient.getQueryCache().subscribe
) can do that.
To put param in the routing is another method to share data between components, but React.Context is better suit for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With