TanStackT
TanStack9mo ago
4 replies
worthy-azure

validateSearch resets router context

Hi,
currently I'm trying to use the validateSearch to get search params inside my loader.


const searchSchema = z.object({
  includeExpired: fallback(z.boolean(), false).default(false),
});

const Route = createFileRoute(
  '/$locale/$departmentId/staff',
)({
  component: RouteComponent,

  context: () => ({ title: 'Staff' }),

  validateSearch: zodValidator(searchSchema),

  loaderDeps: ({ search: { includeExpired } }) => ({
    includeExpired,
  }),

  loader: async ({
    context: { queryClient },
    params,
    deps: { includeExpired },
  }) => {
    // artificial timeout to see loader
    await new Promise(r => setTimeout(r, 2000)); 

    return {
      staff: await queryClient.ensureQueryData(
        staffQueryOptions.list(params.departmentId, {
          includeExpired,
        }),
      ),
    };
  },
});

function RouteComponent() {
  const data = Route.useLoaderData();

  return <UserList users={data.staff} />;
}


My Root-Route looks like this:
export const Route = createRootRouteWithContext<{
  queryClient: QueryClient;
  me: TMe;
  departments: TDepartmentList;
  title: string;
}>()({
  beforeLoad: async ({ context: { queryClient } }) => ({
    me: await queryClient.ensureQueryData(userQueryOptions.me),
    departments: await queryClient.ensureQueryData(departmentQueryOptions.list),
  }),

  component: RootComponent,
});


At some point the router-context seems to be cleared, but only if I use the validateSearch function and call the page without search param (like /en/12345/staff).

It works fine, when:
1. I call the page with the search param (like /en/12345/staff?includeExpired=false)
1. I do not use validateSearch

Any ideas how I can get it to work, calling the page without the search param (because it should be defaulted by the validator) and using the validator?
image.png
Was this page helpful?