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

Posts.svelte

67 lines1.5 KB

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