T
TanStack13mo ago
passive-yellow

How to use useSearch from multiple routes?

I have two routes /posts and /posts/$pId. The /posts route defines search params with validateSearch. In a custom hook I use getRouteApi("/posts") to receive the useSearch hook and access the search params. That's fine so far:
const route = = getRouteApi("/posts/");

export function useGetPosts() {
const userId = route.useSearch({
select: (s) => s.user_id,
});

// do stuff with user_id from URL
}
const route = = getRouteApi("/posts/");

export function useGetPosts() {
const userId = route.useSearch({
select: (s) => s.user_id,
});

// do stuff with user_id from URL
}
When I create links to /posts/$pId, I always copy all search params to the new link so that they are available in the URL also when /posts/$pIdis active. But when I use my custom hook in a component that is rendered when /posts/$pId is active, useSearch fails with Invariant failed: Could not find an active match from "/posts/" Is there any way that i can access the search params in a typesafe way from two different routes, that share the same search params? Thanks a lot!
4 Replies
passive-yellow
passive-yellowOP13mo ago
I think useSerach ("global" one, not from getRouteApi) with strict: false works in this case.
other-emerald
other-emerald13mo ago
it works, but you will get all params as potentially undefined if that's ok, go for it another solution would be to pass the routeid into the custom hook
passive-yellow
passive-yellowOP13mo ago
Thanks, @Manuel Schiller . In my case, that will work as all my search params are optional anyway and thus potentially undefined. For the routeid: is there a TypeScript type i could use for my hook parameter?
other-emerald
other-emerald13mo ago
that should work:
type Ids = RouteIds<RegisteredRouter['routeTree']>
type Ids = RouteIds<RegisteredRouter['routeTree']>

Did you find this page helpful?