Next router is possibly undefined, leading to query with undefined input
Im making a page where i need to query info from my db based on the dynamic route, but my router sometimes returns undefined leading to an annoying error where a query is fired off with an undefined input. Other than doing a || " " what is the way to do this properly using t3?
18 Replies
looking at @tom 's "Build a Blog With the T3 Stack - tRPC, TypeScript, Next.js, Prisma & Zod" video, it appears he gets this error too on his dynamic route, rejecting the first, undefined query, then accepting the updated string query
(apologies for @ ing you)
useRouter is a hook, so it won't be available when the component first renders. You have 2 solutions:
1. Get the prop from the router then conditionally render the component with the query when it's ready, may cause issues
2. Use the enabled prop on the query so it's only enabled when the prop is ready
Or you could use getServerSideProps if you wanted to go down that route
ok, option 2 sounds like the most promising one as trying to avoid server side propsing it, and conditionally rendering sounds like a hassle
not 100% sure what you mean by "enabled prop on query"
The API might be different for tRPC but it exists in react query
Disabling/Pausing Queries | TanStack Query Docs
If you ever want to disable a query from automatically running, you can use the enabled = false option.
When enabled is false:
yep it works, but still shows me the annoying red squiggle, may just //@ts-ignore it
thank you so much! I didnt even know there are options after the input!
Do
const packID = query... as string
tRPC wraps react query and react query has a tone of useful options
yeah casting as string is what i do too
you can also drop the !== and just keep packID or do !!packId
Theres also router.isReady on the router you can use as another option
true, thanks!
Personally I like to wrap them in a Boolean constructor, instead of using !!
Boolean(packID)
Boolean(packID) && typeof packID === 'string'
is also a option
the typeof === is just to let ts know that it is correctooo yeah this is definitely more explicit
So many ways to see if something is defined 😦
ty js
simple booleans were not enough
(IM SHADING TRUTHY/FALSEY)