Reputation: 51
I want to use programmatic navigation in sveltekit, sending in the same time params to the route I want to navigate to. I know there is the goto method that I can use for programmatic navigation but I can't use it to also send params in navigation.
For example in vue js, it can be done like this:
router.push({ name: 'user', params: { userId: '123' } })
How can this be done in sveltekit?
Thank you!
Upvotes: 5
Views: 3315
Reputation: 29917
Indeed $app/navigation is used for programmatic navigation, but it only accepts a string.
To create a string from params you can use a
URLSearchParams object.
I've created a small utility function to generate the urls ( REPL ):
export default function buildUrl(path, params) {
const query = { ...params };
let interpolatedPath = path;
for (const [param, value] of Object.entries(params)) {
const replaced = interpolatedPath.replace(`[${param}]`, value);
if (replaced !== interpolatedPath) {
interpolatedPath = replaced;
delete query[param];
}
}
const search = new URLSearchParams(query).toString();
return `${interpolatedPath}${search ? `?${search}` : ""}`;
}
Usage:
import { goto } from "$app/navigation";
const url = buildUrl('/users/[user]', {user: 123, tab: 'settings'}));
goto(url); // "/users/123?tab=settings"
Upvotes: 3
Reputation: 481
You can navigate via goto
/href
with url search params and then parse these parameters in load
function.
`/your_route/?name=${userName}&id=${userId}`
Upvotes: 0