PuzzlesP
tRPC3y ago
3 replies
Puzzles

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} />;
};

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.
Was this page helpful?