tRPCttRPC
Powered by
PuzzlesP
tRPC•3y 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} />;
};
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
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
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.
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

useQuery returning old data with new params
uzelacUuzelac / ❓-help
3y ago
Query string params
GeeGGee / ❓-help
3y ago
How to call useQuery with params inside JSX
SonSSon / ❓-help
3y ago
Optional query params with open api ?
germiGgermi / ❓-help
2y ago