Next.js dynamic route param typesafety

Is there a better solution than this? Feels annoying to do this for every dynamic route.
// [userId].tsx

const UserPage: NextPage = () => {
const { query } = useRouter();

const userId =
(Array.isArray(query.userId) ? query.userId[0] : query.userId) || "";

return <div>{userId}</div>;
};
// [userId].tsx

const UserPage: NextPage = () => {
const { query } = useRouter();

const userId =
(Array.isArray(query.userId) ? query.userId[0] : query.userId) || "";

return <div>{userId}</div>;
};
2 Replies
esponges
esponges3y ago
I was wondering the same. I had to implement something similar and it sucks. useRouter query is just not cool
needmorewood
needmorewood3y ago
idk if this is a good idea, but could u potetially as string the query if you "know" its always going to be a single thing you can always put this into a hook as well that you pass the query param you want and make it reusable idk the anatomy of react hooks too much but i have worked with vue composables to do something very similar which are similar
Want results from more Discord servers?
Add your server