T
TanStack2y ago
absent-sapphire

Default Search Params

Based on the documentation and the example projects, it seems like you should be able to set default search parameters either by returning a default parameter in validateSearch, or using a preSearchFilter. For example if I have:
export const exampleRoute = createRoute({
getParentRoute: () => rootRoute,
path: "example",
validateSearch: z.object({
myParam: z.nativeEnum(["one", "two"]).default("one")
})
//...
});
export const exampleRoute = createRoute({
getParentRoute: () => rootRoute,
path: "example",
validateSearch: z.object({
myParam: z.nativeEnum(["one", "two"]).default("one")
})
//...
});
This should run before the route and child component render, so when using
// SomeComponment.tsx
const { myParam } = exampleRoute.useSearch();
// SomeComponment.tsx
const { myParam } = exampleRoute.useSearch();
It should be "one" by default, right? I've also tried setting it in the preSearchFilters but am unable to get a default value to populate when navigating to the route with a Link component. Does useSearch() actually run before validateSearch? Edit: for clarification - I am able to set a default, but it doesn't get populated into the URL's search params. So the value in myParam is what I expect but the URL for the page looks wrong because nothing is populated for that param.
4 Replies
adverse-sapphire
adverse-sapphire2y ago
I tend to use the .catch method from zod, as I've gotten more consistent behaviour from it. https://stackblitz.com/edit/github-cqxxd6?file=src%2Froutes%2Fabout.tsx
Sean Cassiere
StackBlitz
router zod default search param - StackBlitz
Run official live example code for Router Quickstart File Based, created by Tanstack on StackBlitz
flat-fuchsia
flat-fuchsia2y ago
I agree since you never know what gets put into the URL, but it still feels like it's a bug that the default value is not populated into the search params. It could also be intended that you want a default value AND a catch value.. e.g. if the param is not provided it resolves to the default value but if somehow the url was malformed and the validation fails the app reacts differently to it.
absent-sapphire
absent-sapphireOP2y ago
Thanks for the insight. I'll open a bug ticket and see what comes of it It's a little tough to tell from the Stackblitz example because the URL doesn't populate, but this populates the search parameter for use by useSearch but it doesn't actually put anything in the URL, is that correct? I was hoping to have the default value appear in the URL as well. Would I need a redirect for that?
passive-yellow
passive-yellow2y ago
I have a very similar problem, the zod catch somewhat solves that, but it only runs the first time my layout is rendered. When clicking links it is not revalidated, I guess? Did some more testing and it actually still sets the searchParam but it is not visible in the URL anymore...

Did you find this page helpful?