Is there a way to monitor queries from a parent component?
Hello! I'm currently trying to figure out the best way to monitor queries in a parent component that are happening in children components.
Consider something like this:
Each
ChildComponent
will be doing requests using useQuery
, useQueries
, etc. Sometimes those requests will return with an authorization error. In those cases, I want to monitor that happened and then render the NoAuthFallbackPage
component instead of children
in the PermissionGate
component.
My thinking was that I could look at the QueryCache in the PermissionGate
component and see if we're getting an authorization error from the backend in our response body, but I'm not sure of the best way to do that. Here are solutions I've considered:
- QueryCache API. This seemed like the way to go since I can easily monitor all queries. Originally I intended to have this in my PermissionGate
component but it appears this is meant to be run "outside" of the React runtime.
- QueryObserver API. This seems to work very well as I have the entire request (status, data, etc) of a query I want to observe. But the issue is it requires the same query key and query function, which might not always be easy to get from a child component to a parent component.
- Utilizing ErrorBoundary
. I was able to get this to work by essentially making the PermissionGate
component an ErrorBoundary
. Then, by passing throwOnError: true
as an option to my queries in my ChildComponent
s, I could check the error that was thrown and if it contained the authorization code, I'd render the NoAuthFallbackPage
component instead. So far this seemed to be the easiest method to get working.
Anyway, I'd love some more thoughts on this. It seems like observing queries running in child components from some arbitrary parent component could be a powerful pattern, and I'm guessing people have run into similar situations like this before, so I'd love to hear your experiences. Thank you!QueryCache | TanStack Query Docs
The QueryCache is the storage mechanism for TanStack Query. It stores all the data, meta information and state of queries it contains.
Normally, you will not interact with the QueryCache directly and instead use the QueryClient for a specific cache.
QueryObserver | TanStack Query Docs
QueryObserver
The QueryObserver can be used to observe and switch between queries.
2 Replies
like-gold•2y ago
throwOnError
throws to errorboundaries is good for this I think
can also be a function that only throws on specific errorseastern-cyanOP•2y ago
Thanks for the suggestion. I didn't actually realize throwOnError could be a function, that is really neat. Definitely gives some more granular control over this process.