SvelteKit How to Reload Current Page via the Client Side Router using Goto?
Asked Answered
M

2

6

It appears that goto in SvelteKit does not do anything when it is instructed to redirect to the current webpage:

<script>
    import { goto, invalidate } from '$app/navigation';

    function reloadPage() {
        const thisPage = window.location.pathname;
        console.log('goto ' + thisPage);
        goto(thisPage);
    }
</script>

<button on:click={() => reloadPage()}>
    Reload
</button>

In addition, I've tried invalidate, as well as invalidate followed by a goto, as well as goto with adding fake query parameters, and none of them will cause the page to refresh.

The only way I can get it working is by calling location.reload(), however this will bypass SvelteKit's client side routing and go back to the server, reloading the entire app over the network.

Mancini answered 7/4, 2023 at 16:32 Comment(0)
S
10

You should not use goto, instead use invalidateAll.

If your page does not appear to update correctly, you are not using the data reactively, i.e. some value is set once and does not update when the data is re-loaded.

Sandpaper answered 7/4, 2023 at 19:28 Comment(4)
this doesn't work when using load function at +page.server.tsSapsucker
@Sapsucker Whether it is in +page or +page.server should not matter at all. (Tested with server file and works just fine.)Sandpaper
invalidateAll should not be called on server. You will get Error: Cannot call invalidateAll() on the server if you do so. SvelteKit maintainer explained it in a GitHub discussion: github.com/sveltejs/kit/discussions/9683Issi
@Kennith: invalidateAll like goto is a page function, so of course you cannot call it on the server. What I was referring to is that it does not matter whether the data is loaded via a load in +page or +page.server, either will be called again on invalidation.Sandpaper
M
3

Here is a workaround, by chaining goto, but there must be a better way:

    function reloadPage() {
        const thisPage = window.location.pathname;

        console.log('goto ' + thisPage);

        goto('/').then(
            () => goto(thisPage)
        );
    }
Mancini answered 7/4, 2023 at 16:44 Comment(2)
it works cool when using load function at +page.server.tsSapsucker
you need to use redirect in server files. goto is not available on server, it will throw Error: Cannot call goto(...) on the serverIssi

© 2022 - 2024 — McMap. All rights reserved.