TanStackT
TanStack3mo ago
4 replies
dead-brown

zod validateSearch without redirecting

I'm running into an issue where the outer route does:

export const Route = createFileRoute("/groups")({
  beforeLoad: () => ({
    queries: {
      summary: something(),
    },
  }),
  loader: async ({ context: { queryClient, queries } }) => {
    return queryClient.ensureQueryData(queries.summary)
  },

and the inner route does:
export const Route = createFileRoute("/groups/$groupId")({
  params: {
    parse: ({ groupId }) => ({ groupId: Number(groupId) }),
  },
  validateSearch: (search) => searchSchema.parse(search),

The zod schema is a looseObject with a bunch of default() fallbacks:
const searchSchema = z.looseObject({
  numbers: z.array(z.number()).default([1, 2, 3]),
  other: z
    .array(z.enum(...))
    .default(...),


When I navigate to the page without any search params, it works fine and I get immediately redirected (?) to a URL that has all the search params that have zod .default() specified explicitly - I am fine with this behavior. But when I navigate (through a specific URL, in a new tab) to this page with just one of the schema parameters specified, the page crashes in the outer route's loader function.

Upon inspection, context.queries ends up being undefined. Any ideas why this happens?

My workaround is to do this for validateSearch:
  validateSearch: (search) => {
    searchSchema.parse(search);
    return search;
  },


This prevents the route component replacement/redirect but still detects parsing errors like it should
Was this page helpful?