Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React-Query QueryCache from another component

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.

like image 954
Edelmann Avatar asked Sep 22 '20 08:09

Edelmann


2 Answers

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.

like image 70
TkDodo Avatar answered Oct 16 '22 22:10

TkDodo


To put param in the routing is another method to share data between components, but React.Context is better suit for it.

like image 1
Denis Irkhin Avatar answered Oct 16 '22 22:10

Denis Irkhin