T
TanStack2w ago
unwilling-turquoise

Is it possible to convert a SearchParam string to a valid LinkOption?

I have a URL search parameter called return_to that contains a URL that may exist within my application like this ?return_to=https//app.foundry-dev.ac/org/settings/billing/credit (URL decoded so it's easier to read here) I can access that param like this const return_to = Route.useSearch({ select: ({ return_to }) => return_to }) When I submit a form, I want to take this query param and navigate to it. I would want to do something like this (pseudo code)
const linkOption = parseUrlToLinkOption(return_to) // returns a type of LinkOption | undefined

// if there is a valid route in my app, linkOption will be defined
if (linkOption) {
navigate(linkOption)
} else {
navigate({ href: return_to }) // just fall back to href navigation if we cant do client side routing
}
const linkOption = parseUrlToLinkOption(return_to) // returns a type of LinkOption | undefined

// if there is a valid route in my app, linkOption will be defined
if (linkOption) {
navigate(linkOption)
} else {
navigate({ href: return_to }) // just fall back to href navigation if we cant do client side routing
}
I think I'm sort of on the right track because I see there is a parseHref method in @tanstack/history and a parseLocation() that takes a parsed href, but that returns a ParsedLocation and not something I can pass in to navigate (i think).... Is something like this possible? Or how can I take a URL from a query parameter and use it for client side routing? I figure this is how Router loads in the initial route from the URL on page load but I can't find that code yet... Thanks as always : )
4 Replies
deep-jade
deep-jade2w ago
you probably would need to match the location against the route tree. does this encoded url contain search params?
unwilling-turquoise
unwilling-turquoiseOP2w ago
Oh hmm interesting. Once I run parseLocation I would need to use a prop from ParsedLocation and compare it to a route in my generated route tree file (or something returned in useRouter)? Yea it would be ideal to support any form of URL including search parameters. If it’s not something i can build out from a library function maybe I need to rethink my implementation…. I was hoping something existed because then i could take that same logic and apply it to a “back button” on the form too. Where the route from the return_to param in the URL is what determines where that back button routes to as well (using the Link component natively)
deep-jade
deep-jade2w ago
Router type | TanStack Router React Docs
The Router type is used to describe a router instance. Router properties and methods An instance of the Router has the following properties and methods: .update method Type: (newOptions: RouterOptions...
unwilling-turquoise
unwilling-turquoiseOP2w ago
nice! that might work, thanks, I'll report back if I get this to work with a solution

Did you find this page helpful?