How to pass trpc useQuery into a component
Hello, I'm wondering how I can tell typescript what type my
useQuery
is when passing it into a react component? I want to avoid using any
.
I am aware of RouterOutputs
, but this doesnt work for the entire useQuery response, only for the data
that is returned.
4 Replies
the reason im trying to pass this in is because I am using a tabs system and I originally had the
useQuery
inside of there but everytime i switched tabs the data would refetch, so i just moved it up a component to prevent that@Peform
You can use ReturnType to type whole object, like this
type GetPremiumGuildsQueryType = ReturnType<typeof api.premium.getPremiumGuildIds.useQuery>;
it includes like data, error, isloading, refetch, status
you can avoid to use any
define type first instead of using hook directlythank you! 🙂
will give this a try soon.
1.
UseQueryResult<User, Error>
from here https://github.com/TanStack/query/discussions/7358#discussioncomment-9287648 sounds like what you're looking for.
2. But I personally would prefer to pass down the query itself. It's the thing you would pass in const { data } = useQuery(THE_THING)
if you were using Tanstack Query without tRPC. (I believe there is a proper Query type that I don't know off the top of my head, check what useQuery expects as a param.)
Then you could use the query with useQuery
in the consumer down the tree where you need the data. If the point in time when the data is fetched is a concern, you can queryClient.prefetchQuery
at the place where you would've called useQuery originally.
The only problem is that tRPC's "Classic" Tanstack Query integration doesn't expose the queries directly. You'd have to migrate to the new tanstack query integration: https://trpc.io/docs/client/tanstack-react-query/migrating. It's completely doable in an evening and you can also migrate incrementally because "Both clients are compatible with each other and can exist in the same application"