Select option for QueryClient.getQueryData or allow useQuery select without queryFn #8452
Replies: 2 comments 1 reply
-
Now that I think about it, |
Beta Was this translation helpful? Give feedback.
-
This is a typical client state management problem. You have some filters / params / whatever that you need to have available everywhere in your app. If you don’t want prop drilling, I’d suggest putting them somewhere into a global client state manager like redux or zustand. Then, your custom useQuery hook becomes:
I’m going into this in my talk “Thinking in React Query”: https://tkdodo.eu/blog/thinking-in-react-query |
Beta Was this translation helpful? Give feedback.
-
I may be misunderstanding something here, but as far as I'm aware,
select
is only possible with useQuery, there isn't an option to do that when directly selecting from the cache. And I'm making a second assumption here, that the following code will trigger a rerender every time any part of the cached data changes, whileselect
offers the possibility for partial subscription:If my two assumptions are correct, this presents a bit of a problem for me: I'm migrating away from Redux, and my current architecture relied heavily on partial store subscriptions, something I don't want to lose. I also have a standardised api, so I wrap
useQuery
,useInfiniteQuery
, etc. within custom hooks, so that I can automate some functionality which I'd otherwise need to duplicate, like auth headers, auto generating query keys, etc.I'd also like to have reusable selectors, since I know the exact structure of the api response, which is the same for every response. But here is where I run into a problem: I cannot rely on
useQuery
'sselect
option most of the time, since it would require me to make unmaintainable prop drilling to relevant components.InfiniteList
component, which gets the following props:resourcePath, pageSize, filter, order, include
, etc. If I relied onuseQuery
'sselect
option to build the selectors for partial data further down the tree(components which are memoized, so they don't rerender whenever a new page is fetched), I'd need to prop drill all query dependencies down and to reconstruct theuseQuery
at the top of the tree, which quickly becomes unmaintainable. And the way the component is, it requires hook-based subscription, I cannot just simply pass down the relevant data in the tree, since I would lose composability and extendability within the InfiniteList context.This is not a pattern I'd like to move away from, however there is a simple solution: allow
useQuery
to act only as a selector, returning undefined when noqueryFn
was provided(I may be mistaken, but or add a select option togetQueryData
. I may be mistaken, since the types don't requirequeryFn
, but I get a runtime error ofMissing queryFn
if I don't provide one.To clarify further, the current paradigm for writing selectors is this:
I'd like to be able to do this:
Beta Was this translation helpful? Give feedback.
All reactions