Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

Posts.svelte

60 lines1.3 KB

1<script lang="ts">
2 import { useQueryClient, createQuery } from '@tanstack/svelte-query'
3 import { getPosts } from './data'
4​
5 const client = useQueryClient()
6​
7 let limit = 10
8​
9 const posts = createQuery<
10 { id: number; title: string; body: string }[],
11 Error
12 >({
13 queryKey: ['posts', limit],
14 queryFn: () => getPosts(limit),
15 })
16</script>
17​
18<div>
19 <div>
20 {#if $posts.status === 'pending'}
21 <span>Loading...</span>
22 {:else if $posts.status === 'error'}
23 <span>Error: {$posts.error.message}</span>
24 {:else}
25 <ul>
26 {#each $posts.data as post}
27 <article>
28 <a
29 href={`/${post.id}`}
30 style={// We can use the queryCache here to show bold links for
31 // ones that are cached
32 client.getQueryData(['post', post.id])
33 ? 'font-weight: bold; color: indianred'
34 : 'cursor: pointer'}
35 >
36 {post.title}
37 </a>
38 </article>
39 {/each}
40 </ul>
41 {#if $posts.isFetching}
42 <div style="color:darkgreen; font-weight:700">
43 Background Updating...
44 </div>
45 {/if}
46 {/if}
47 </div>
48</div>
49​
50<style>
51 article {
52 text-align: left;
53 }
54 a {
55 display: block;
56 color: white;
57 font-size: 1.5rem;
58 margin-bottom: 1rem;
59 }
60</style>