TanStackT
TanStack2y ago
6 replies
dead-brown

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
}


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!
Was this page helpful?