Rendered more hooks than during the previous render Typescript error

Hey, I have a parameter on my page that im loading with with router.query. This is what my code looks like const { studentId } = router.query; if (typeof studentId !== "string") { return null; } else { const studentQp = api.coach.getStudentQps.useQuery({ studentId: studentId, }); rest of my code.... I did it this way to ensure typesafety, but if i put all of the trpc querys at the beginning of the page, i get typescript errors because the type of studentId is not checked first How do i solve this?
12 Replies
Neto
Neto•17mo ago
if cant use hooks conditionally
const { studentId } = router.query;

const studentQp = api.coach.getStudentQps.useQuery({
studentId: studentId as string, // will be a string, because enabled will validate first
},
{
enabled: typeof studentId === "string" // this thing here
}
);
const { studentId } = router.query;

const studentQp = api.coach.getStudentQps.useQuery({
studentId: studentId as string, // will be a string, because enabled will validate first
},
{
enabled: typeof studentId === "string" // this thing here
}
);
enabled will block the query execution until studentId is defined and a string
Christian Lind
Christian LindOP•17mo ago
tried that, and i thought that that should have worked
Christian Lind
Christian LindOP•17mo ago
Neto
Neto•17mo ago
force as string i corrected the snippet above
Christian Lind
Christian LindOP•17mo ago
you are a star thanks
Neto
Neto•17mo ago
you have to studentId as string or studentId as unknown as string
Christian Lind
Christian LindOP•17mo ago
whats the difference with as string and as unknown as string? Ive seen as unknown followed by as type quite a few times but never understood it
Neto
Neto•17mo ago
sometimes you can't cast directly like Type1 -> Type2 but you know that it will be the correct type using as unknown is telling to ts: "really trust me, bro"
Christian Lind
Christian LindOP•17mo ago
alright 🙂 thx!
barry
barry•17mo ago
Set enabled to !!studentid in the use query options instead of optionally calling a hook Ah didn’t see fixed
Christian Lind
Christian LindOP•17mo ago
One more related question
Christian Lind
Christian LindOP•17mo ago
Im often seeing these errors "Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the void operator." i usually just add a void before and then all is good - but is this considered bad practice?
Want results from more Discord servers?
Add your server