T
TanStack11mo ago
rare-sapphire

Typesafety on use useLocation

Hey all! Not sure if Im doing something wrong or if I just don't understand what should be happening here: Im trying to get typesafety on useLocation(), example:
const location = useLocation();
location.pathname === "" // <<<< Should I be having my paths autocomplete here??
const location = useLocation();
location.pathname === "" // <<<< Should I be having my paths autocomplete here??
I assumed, yes, I should be getting autocomplete here. But the type is just ParsedLocation<{}>.pathname: string Not sure if it helps, but I am using a hash router (I know I know, unfourtunately can't do anything about it) Thanks!
8 Replies
constant-blue
constant-blue11mo ago
what do you try to achieve in the end? most likely useMatches will give you the typesafety you want, but I need more details
rare-sapphire
rare-sapphireOP11mo ago
So like when I use navigate({to: "" << this autocompletes with my pages I can navigate to}) I assumed I could use that with useLocation as well, where I get a list of my paths as types
constant-blue
constant-blue11mo ago
hm no you get the actual path, which also can contain path params does useMatches work for you?
rare-sapphire
rare-sapphireOP11mo ago
useMatches does give me that, but its not dependant of the current path. Maybe I should have given more details on how I want to use it: I have one component which I want to mount at the top level, inside the "root route" component. This component is a interactive app tour type thing. It needs to perform some steps, depending on which page I am on. Example:
const routeSteps = {
"/": [stepOne, steptwo....],
"/about": [aboutStepOne, aboutStepTwo....],
const routeSteps = {
"/": [stepOne, steptwo....],
"/about": [aboutStepOne, aboutStepTwo....],
Then in the component I wanted to do something like const location = useLocation() const steps = routeSteps[location.pathname] But as you said this does not take search params into consideration. Is my approach here just completely wrong?
constant-blue
constant-blue11mo ago
why is useMatches not dependent on the current path?
eastern-cyan
eastern-cyan3mo ago
sorry to revive this but have a similar need where I want to highlight a piece of non-interactive UI that's part of a layout route based on the current route. is the recommendation to use useMatches in the layout route for something like this? What's the best way of getting the current route using useMatches? something like useMatches()[-1] ?
constant-blue
constant-blue3mo ago
how do you define "current route" ? if you mean the leaf route of the currently matched routes, then yes you can use the last entry in the matches array
eastern-cyan
eastern-cyan3mo ago
yeah exactly. i ended up using useChildMatches and taking the last entry, which seems to achieve my goal

Did you find this page helpful?