-
-
Save norricorp/011edb9f70280772f215797ee9203416 to your computer and use it in GitHub Desktop.
svelte and pagination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
import { onMount } from "svelte"; | |
// @ts-ignore | |
import { paginate, PaginationNav } from 'svelte-paginate' | |
import Hero from "../components/Hero.svelte"; | |
import Article from "../components/Article.svelte"; | |
import { directus } from "../services/directus"; | |
import { formatRelativeTime } from "../../../shared/utils/format-relative-time"; | |
let hero, articles; | |
export let members = false | |
let currentPage = 1 | |
let pageSize = 3 | |
async function fetchData() { | |
const response = await directus.items("articles").readByQuery({ | |
fields: ["*", "author.avatar", "author.first_name", "author.last_name"], | |
filter: { | |
membersOnly: members, | |
}, | |
// @ts-ignore | |
sort: "-publish_date", | |
}); | |
const formattedArticles = response.data.map((article) => { | |
return { | |
...article, | |
// @ts-ignore | |
publish_date: formatRelativeTime(new Date(article.publish_date)), | |
}; | |
}); | |
const [first, ...rest] = formattedArticles; | |
hero = first; | |
articles = rest; | |
} | |
onMount(fetchData); | |
$: paginatedItems = paginate({ items: articles, pageSize, currentPage }) | |
</script> | |
<main> | |
<section class="main-content"> | |
<div class="container"> | |
{#if hero} | |
<Hero article={hero} /> | |
{/if} | |
{#if articles} | |
<div class="articles-grid"> | |
{#each paginatedItems as article, index} | |
<Article {article} bordered={index !== articles.length - 1} /> | |
{/each} | |
</div> | |
{/if} | |
</div> | |
<PaginationNav | |
totalItems="{articles.length}" | |
pageSize="{pageSize}" | |
currentPage="{currentPage}" | |
limit="{1}" | |
showStepOptions="{true}" | |
on:setPage="{(e) => currentPage = e.detail.page}" | |
/> | |
</section> | |
</main> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment