-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathLoadMore.svelte
More file actions
64 lines (59 loc) 路 1.54 KB
/
Copy pathLoadMore.svelte
File metadata and controls
64 lines (59 loc) 路 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<script lang="ts">
import { createInfiniteQuery } from '@tanstack/svelte-query'
const endPoint = 'https://swapi.dev/api'
const fetchPlanets = async ({ pageParam = 1 }) =>
await fetch(`${endPoint}/planets/?page=${pageParam}`).then((r) => r.json())
const query = createInfiniteQuery(() => ({
queryKey: ['planets'],
queryFn: ({ pageParam }) => fetchPlanets({ pageParam }),
initialPageParam: 1,
getNextPageParam: (lastPage) => {
if (lastPage.next) {
const nextUrl = new URLSearchParams(new URL(lastPage.next).search)
const nextCursor = nextUrl.get('page')
if (nextCursor) {
return +nextCursor
}
}
return undefined
},
}))
</script>
{#if query.isPending}
Loading...
{/if}
{#if query.error}
<span>Error: {query.error.message}</span>
{/if}
{#if query.isSuccess}
<div>
{#each query.data.pages as { results }}
{#each results as planet}
<div class="card">
<div class="card-body">
<h2 class="card-title">Planet Name: {planet.name}</h2>
<p>Population: {planet.population}</p>
</div>
</div>
{/each}
{/each}
</div>
<div>
<button
onclick={() => query.fetchNextPage()}
disabled={!query.hasNextPage || query.isFetchingNextPage}
>
{#if query.isFetching}
Loading more...
{:else if query.hasNextPage}
Load More
{:else}Nothing more to load{/if}
</button>
</div>
{/if}
<style>
.card {
background-color: #111;
margin-bottom: 1rem;
}
</style>