puzzles9351
puzzles935113mo ago

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.
1 Reply
Maj
Maj13mo ago
u can do enabled: router.isReady
const router = useRouter();
const { categoryId } = router.query;
const { data: categoryProducts, isFetched } = api.category.getCategoryItems.useQuery(
{ name: categoryId as string[] },
{ enabled: router.isReady, refetchOnWindowFocus: false },
)
const router = useRouter();
const { categoryId } = router.query;
const { data: categoryProducts, isFetched } = api.category.getCategoryItems.useQuery(
{ name: categoryId as string[] },
{ enabled: router.isReady, refetchOnWindowFocus: false },
)
This is how i use it.