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
Max
Max•2y ago
Max
Max•2y ago
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
Max
Max•2y ago
(apologies for @ ing you)
tom0619
tom0619•2y ago
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
Max
Max•2y ago
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"
tom0619
tom0619•2y ago
The API might be different for tRPC but it exists in react query
tom0619
tom0619•2y ago
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:
Max
Max•2y ago
Max
Max•2y ago
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!
tom0619
tom0619•2y ago
Do const packID = query... as string tRPC wraps react query and react query has a tone of useful options
Keef
Keef•2y ago
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
Max
Max•2y ago
true, thanks!
tom0619
tom0619•2y ago
Personally I like to wrap them in a Boolean constructor, instead of using !! Boolean(packID)
Neto
Neto•2y ago
Boolean(packID) && typeof packID === 'string' is also a option the typeof === is just to let ts know that it is correct
Keef
Keef•2y ago
ooo yeah this is definitely more explicit
Want results from more Discord servers?
Add your server