Type narrowing for hook that has multiple queries
Hey folks, I'm wondering if someone can help me figure this query/typescript issue out. For the useQuery hook it's well known that if you look for isPending and isError then you get some helpful type narrowing on the data.
My question is how to create a hook that wraps multiple useQueries and returns type narrowing for all the returned data.
Here's a stripped down version of the hook
I'd like to be able to do use this hook like the following:
Without there being a type error. I think we can be certain that data exists at the point of the log statement, right? So how can I structure my hook to have proper type narrowing?
5 Replies
equal-jade•8mo ago
what do you need that https://tanstack.com/query/latest/docs/framework/react/reference/useQueries with the combine function doesn't already provide?
useQueries | TanStack Query React Docs
The useQueries hook can be used to fetch a variable number of queries: tsx const ids = [1, 2, 3] const results = useQueries({ queries: ids.map((id) = ({ queryKey: ['post', id], queryFn: () = fetchPost...
fair-roseOP•8mo ago
I didn't realize this api existed. Thank you. Thank you this is exactly what I need!
Actually, I realized this won't work because I have dependent queries, so I'm still looking for a good ts solution
equal-jade•8mo ago
you mean some of the queries are dependent on other queries in the same array?
fair-roseOP•8mo ago
yes precisely. And I all my single queries are defined in useQuery hooks so I'd rather not have multiple sources of truth for querying a particular endpoint.
I think the code above works fine, but it's weird to me that TS can't manage automatic type narrowing.
equal-jade•8mo ago
Could you maybe make the queries dependent on the combined result?