8

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.

2
  • 3
    Since selectedStore is UI client state we need to store in global state or nearest possible component hierarchy via context API, zustand or redux etc, Then from other component we can fetch the cached data. Commented Oct 1, 2020 at 15:46
  • 1
    Ya u need to follow what raja mentioned or make the cache key just products and the cache will only have the latest data. But then u sorta loose the benefits caching and react-query. Commented Jan 10, 2021 at 9:18

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.