Using dynamic Param slug in TRPC query

I seem to go in ups and downs in my love of TypeScript (I shouldn’t say that here tho 🙂 ) In a page, I would like to pass the slug of that page to a TRPC api call as follows: const router = useRouter() const { slug } = router.query const { data: options } = api.product.getOptions.useQuery({ id: slug }) However, doing so I get type errors on slug (specifically that it could be undefined, string or string[] I have tried both doing a type check and then returning when it’s not a strinf but this leads to an error around ‘more hooks rendered than during previous render’ or by trying enabled but this doesn’t seem to solve it. What is the proper way to use the slug directly in a TRPC query?
5 Replies
cje
cje16mo ago
cast it to a string the way next treats slug typing is dumb
anthonylin198
anthonylin19816mo ago
May not be what you're looking for, but if you get the slug from the server side using the GetServerSidePropsContext type works.
export function getServerSideProps(context: GetServerSidePropsContext) {
const id = context?.params?.id;

return { props: { pageProps: { assessmentId: id } } };
}
export function getServerSideProps(context: GetServerSidePropsContext) {
const id = context?.params?.id;

return { props: { pageProps: { assessmentId: id } } };
}
I recently did something like this:
const ApplicationPage = ({ pageProps: { assessmentId } }: PageProps) => {


const { data: applicationData } =
api.applicantApplication.getApplicationData.useQuery(assessmentId);

console.log("application data", applicationData);

return (
<div>
<div>{applicationData?.title}</div>
</div>
);
};
const ApplicationPage = ({ pageProps: { assessmentId } }: PageProps) => {


const { data: applicationData } =
api.applicantApplication.getApplicationData.useQuery(assessmentId);

console.log("application data", applicationData);

return (
<div>
<div>{applicationData?.title}</div>
</div>
);
};
nickparks
nickparks16mo ago
Love the simplicity of just casting it to a string. Will try both! Thanks folks 2 hours spent staring - dunno why I didn’t try just cast haha
anthonylin198
anthonylin19816mo ago
Haha it happens 😆 , I'm also fairly new to TS
cje
cje16mo ago
i hate casting stuff so i know how you feel but in this situation ive been doing it a lot for over a year now and it has never blown up on me so im ok with it