Looking for example of DataTable to use paginated API #1903
-
I have the following example of a DataTable that uses an API (JSON-LD using hydra collections). For simplicity I ommit the code for fetching but I think it's pretty obvious at this point. What works: It loads the first page without issue, shows the correct number of pages and total items. Switching the number of items per page also works flawlessly. What doesn't work: As soon as you go to page 2, the list is empty. Same for the next pages, it just is always empty. In the network panel I can see the requests being made correctly with pagesize and page number being sent to the api and it replying correctly. My guess is that the component treats the reply from page 2 as if it was page 1, and so it thinks there is no data for page 2. I may just miss something obvious as I'm new to Svelte(Kit) and these components. A good hint would be appreciated, or just a link to where someone has already explained it in detail as I was unable to find a good example of this. Thanks!
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @ChristianRiesen, In order to paginate results loaded server-side, here's what needs to be done:
Example code: <script>
import { goto } from '$app/navigation';
import { DataTable, Pagination } from 'carbon-components-svelte';
import 'carbon-components-svelte/css/white.css';
export let data;
const changePage = async (e) => {
await goto(`?page=${e.detail.page}`);
};
</script>
<h1>Server-paginated table</h1>
<DataTable headers={data.headers} rows={data.rows} />
<Pagination
page={data.page}
totalPages={data.totalPages}
pageSize={5}
totalItems={data.totalItems}
pageSizes={[5]}
on:change={changePage}
/> Working demo using SvelteKit, |
Beta Was this translation helpful? Give feedback.
Hi @ChristianRiesen,
In order to paginate results loaded server-side, here's what needs to be done:
on:change
instead ofbind:
in<Pagination />
to respond to events such as the user clicking on the 'next page' button.<DataTable>
'spage
prop since that will paginate items already available in the table. In your case, there's only ever one page in the DataTable, but multiple pages represented in<Pagination>
.load
methodrows
andpage
values, your Pagination and DataTables will update.Example code: