oleh.lavryk
oleh.lavryk

Reputation: 41

Is there any way to use goto() without reloading page on SvelteKit?

I have one problem: I need to add additional part to url (IE: I have /route and I need to convert it to /route/something without reloading of the page. I’ve tried to use goto(), but it reloads the page. I would be appreciate if someone could help me.

I'll excpect change url params ex: /watchlist/[lang] without reloading, if it possible, by using goto()

Upvotes: 4

Views: 9656

Answers (4)

brunnerh
brunnerh

Reputation: 185225

SvelteKit uses a file system and path based router, so if you change the path, you by default invoke a page change.

One option would be to not make the language part of the path. You could for example pass it as a query parameter or store it in a cookie, storage or server-side with session/user information.

To change the query, you can do something like this:

function onChange() {
    const url = new URL(window.location.href);
    url.searchParams.set('lang', 'en');

    goto(url.href);
    // or this, if you do not want a new history entry:
    goto(url.href, { replaceState: true });
}

If you really want to prevent navigation and keep it in the path, starting with SvelteKit 2, you could use pushState or replaceState to manipulate the history without navigation. There also should be a route for whatever you set the URL to, otherwise a page reload will cause an error as the page will no longer be found.

Upvotes: 4

M Imam Pratama
M Imam Pratama

Reputation: 1311

We can use data-sveltekit-replacestate attribute on a link:

<a data-sveltekit-replacestate href="/path">Path</a>

Upvotes: 1

Strom
Strom

Reputation: 382

This is now possible since SvelteKit v2.0.0 introduced shallow routing.

The two new SvelteKit functions of interest are pushState and replaceState.

These work similarly to the generic Web History API but with the added benefit of properly integrating with SvelteKit so that you get proper data changes and scroll restoration when browsing around in the history stack.

Upvotes: 1

A random guy
A random guy

Reputation: 51

For now, you should use History API instead of sveltekit goto() because goto() will actually navigate to the target page (trigger the load() ) while History API won't. See issue here.

window.history.replaceState(history.state, '', newURL)

Two things to note:

  1. Pass the current state as the first parameter in the replaceState() to avoid messing up sveltekit router.
  2. Make sure you do have a route for the newURL so that a page refresh won't break your app.

Upvotes: 5

Related Questions