How should I type 'prev' search in reusable component? If it is going to be always the same type
🤔

9 Replies
stormy-gold•16mo ago
is
routeId
just any string?
please provide a minimal complete example by forking one of the existing examples on stackblitzabsent-sapphireOP•16mo ago
Hi! I simplified it a lot, but I hope the idea is still understandable. https://stackblitz.com/edit/tanstack-router-6qhvqe?file=src%2Fcomponents%2FReusableComponent.tsx
stormy-gold•16mo ago
so what is the actual question?
prev
has type {title: string}
. is this not what you want?
absent-sapphireOP•16mo ago
Ah, okay, I get it. It's because I simplified the example. In my real project, the Route.id contains '_layout' and other hidden elements, so when I pass it as a prop, useNavigate doesn't accept it. I tried passing Route.fullPath, but then useSearch({ from: fullPath }) doesn't accept fullPath and requires the 'id' type. I ended up passing both and typing them with unions.
absent-sapphireOP•16mo ago

stormy-gold•16mo ago
you don't have to pass in
from
at all
then you will get an object where all search params are merged and optionalabsent-sapphireOP•16mo ago
Okay, I thought this was not a safe way to use the useNavigate and useSearch hooks because of these bits in the documentation: https://tanstack.com/router/latest/docs/framework/react/guide/search-params#usenavigate-navigate-search- and https://tanstack.com/router/latest/docs/framework/react/guide/type-safety#fixing-the-component-context-problem
stormy-gold•16mo ago
There is a few ways to solve this problem and it depends on cross cutting concerns of the component.
- If your component is a true utility component that could be used in any route then
useSearch
, useParams
with strict: false
or useNavigate
without from
or to
can make sense. In this case you will get a merged object of all search
params for all routes
- If your component is cross cutting to only a particular branch and you want to access common search properties from a branch then you can use from
and pass the route id/path of the branch
- If you have a particular set of routes the component can be used on then a union can make sense if you want to restrict it. This is what you're doing above.
I think it depends on your situation and all of these can be valid approaches depending on what you're afterabsent-sapphireOP•16mo ago