0

I’m building a Svelte 4 app with Routify for routing and carbon-components-svelte for UI.

I have a Pagination component that should read the current page from the URL query params ($params.page) and update the URL when the user navigates pages.

Here’s a simplified version of my code:

<script>
    import { Pagination } from "carbon-components-svelte";
    import { writable } from "svelte/store";
    import { goto as $goto, params as $params } from "@roxi/routify";

    export let rows;

    let page = parseInt($params.page) || 1;

    const opts = { limit: 20, offset: 0 };
    const hasNext = new writable(opts.limit);

    if (page > 1) {
        rows.next(hasNext, page);
    }

    function updateQueryParamsPage() {
        const newParams = { ...$params, page };
        $goto(location.pathname, newParams);
    }
</script>

<DataTable
        {headers}
        rows={$rows.data}
        {sortable}
        {stickyHeader}
        {batchSelection}
        {nonSelectableRowIds}
        bind:selectedRowIds
        bind:sortKey
        bind:sortDirection>
        <!-- some code here -->
    </DataTable>
<Pagination
    {page}
    pageSize={opts.limit}
    pageSizes={[opts.limit]}
    totalItems={$rows.count}
    pageSizeInputDisabled
    on:change={(e) => {
        page = e.detail.page;
        rows.next(hasNext, page);
        updateQueryParamsPage();
    }} />

Problem:

Even if I’m on ?page=2 or ?page=3, the Pagination always renders with page 1. Clicking the pagination works, but when reloading or visiting a URL directly with ?page=3, the pagination still shows page 1. I tried using bind:page instead of {page} but the issue is the same.

Expected behavior:

If the URL has ?page=3, the pagination should initialize with page 3. When I click next/prev in the pagination, both the UI and the URL query param should stay in sync.

Question:

How can I correctly sync Routify’s $params.page with Carbon’s component so that the page number doesn’t reset to 1 on load?

1 Answer 1

0

According to my understanding the Pagination component does not render after page value changes, so as an hack I have made following change

{#if $rows.count > 0}
<Pagination
    {page}
    pageSize={opts.limit}
    pageSizes={[opts.limit]}
    totalItems={$rows.count}
    pageSizeInputDisabled
    on:change={(e) => {
        page = e.detail.page;
        rows.next(hasNext, page);
        updateQueryParamsPage();
    }} />
{/if}

I am not sure if this is the correct way to do but this works for me so going with this solution for time being

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.