mako
mako16mo ago

Skipping useQuery with typescript

I'm wondering if there is a way to skip a query in a typescript friendly way? rtk-query has a handy skipToken that can be used to opt out of the query (https://redux-toolkit.js.org/rtk-query/usage-with-typescript#skipping-queries-with-typescript-using-skiptoken). I see that tanstack has an enabled option, however, it seems with the trpc react hook API you must still pass a typesafe query input. Is there anything I'm missing? How is this intended to work?
Usage With TypeScript | Redux Toolkit
RTK Query > TypeScript: Instructions on how to use RTK Query with TypeScript
4 Replies
Nick
Nick16mo ago
Yes you want enabled. I don't follow why type-safety would be a problem though? Type are only checked at compile-time, so if you're assigning an invalid variable to the query enabling/disabling isn't going to help with that
mako
mako16mo ago
If you have an optional parameter to a component and need to run a query conditionally like
const result = trpc.endpoint.useQuery({ param }, { enabled: !!param })
const result = trpc.endpoint.useQuery({ param }, { enabled: !!param })
It will fail the typecheck because { param: undefined } is not a valid query With rtk-query style skip token this would look like
const result = trpc.endpoint.useQuery(param ? { param } : skipToken)
const result = trpc.endpoint.useQuery(param ? { param } : skipToken)
Which can pass type-checking because skipToken is a valid arg to useQuery
Nick
Nick16mo ago
Got it A skip token can just be a variable of type “any”
mako
mako16mo ago
Yes, I can make the types pass with assertions, but keeping 2 arguments in sync is both inconvenient and error prone. I was hoping there was another why which I was missing.