Search code examples
sveltesveltekit

Going back to a url doesn't update the page


There's a page showing a student list. It should support pagination (via ?page=).

Going from ?page=0 to ?page=1 -> page is updated

Going back from ?page=1 to ?page=0 -> page is not updated (unless I pass invalideAll:true - goto('?page=0', { invalidateAll:true })

// +page.ts
import type { PageLoad } from './$types';
export const prerender = true;

export const load: PageLoad = async ({ fetch, url }) => {
    const selected_page = parseInt(url.searchParams.get("page") || "0");
    const res = await fetch(`/api/student-list?page=${selected_page}`); // make sure there are no trailing slashes, otherwise bug https://stackoverflow.com/questions/78734150/sveltekit-redirect-308-when-trying-to-access-internal-api-from-page-server-ts
    const response = await res.json();
    response.selected_page = selected_page + 1;
    console.log("load() selected page=", selected_page);

    return response;
};
<!-- +page.svelte -->
<script lang="ts">
    import Pagination from "../../components/pagination.svelte";

    /** @type {{ data: import('./$types').PageData }} */
    import { page as g_page } from "$app/state";
    import { goto } from "$app/navigation";

    const { data } = $props();
    const _ = $derived(data); // to make sure when 'data' is updated, things are re-rendered
    const __ = $derived(g_page.url.searchParams);

    function page_clicked(page_arg: number) {
        g_page.url.searchParams.set("page", (page_arg - 1).toString());
        goto(g_page.url);
    }
</script>

<Pagination custom_class="mb-8"
    onPageClick={page_clicked}
    selected_page={data.selected_page}
    total={data.total}
/>

Is there a way to fix this? is this by-design?


Solution

  • You should not modify the existing page state URL, it breaks the goto logic which after the first modification will determine that the source and target URLs are the same so nothing happens.

    Create a new URL instead:

    const newUrl = new URL(g_page.url);
    newUrl.searchParams.set("page", (page_arg - 1).toString());
    
    goto(newUrl);
    

    (Modifying the URL in place may work if PR #13196 is merged.)