puzzles9351
puzzles9351
TtRPC
Created by puzzles9351 on 6/23/2023 in #❓-help
useQuery with query params
Hi, I'm wondering how to correctly handle query params as a useQuery input using Nextjs.
const RecipeDetailPage: NextPageWithLayout = () => {
const router = useRouter();

const querySchema = z.object({ id: z.string() });
const query = querySchema.safeParse(router.query);

const recipe = api.recipes.getRecipeById.useQuery(query.data?.id, {
enabled: query.success,
});

if (!recipe.data) return null;

return <RecipeDetail recipe={recipe.data} />;
};
const RecipeDetailPage: NextPageWithLayout = () => {
const router = useRouter();

const querySchema = z.object({ id: z.string() });
const query = querySchema.safeParse(router.query);

const recipe = api.recipes.getRecipeById.useQuery(query.data?.id, {
enabled: query.success,
});

if (!recipe.data) return null;

return <RecipeDetail recipe={recipe.data} />;
};
Since useRouter.query returns undefined on first render, I need to parse the query. This works, however there's still a type error on the query.data?.id, since it could be null, and the query expects a string. What is the right way to handle a situation like this.
4 replies