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

Posts.svelte

50 lines1.2 KB

1<script lang="ts">
2 import { createQuery, useQueryClient } from '@tanstack/svelte-query'
3 import type { Post } from './types'
4​
5 type Props = {
6 setPostId: (postId: number) => void
7 }
8​
9 let { setPostId }: Props = $props()
10​
11 const queryClient = useQueryClient()
12​
13 // All you have to do now is pass a key!
14 const query = createQuery<Array<Post>>(() => ({
15 queryKey: ['/posts'],
16 }))
17</script>
18​
19<div>
20 <h1>Posts</h1>
21 <div>
22 {#if query.status === 'pending'}
23 Loading...
24 {:else if query.status === 'error'}
25 <span>Error: {query.error.message}</span>
26 {:else}
27 <div>
28 {#each query.data as post (post.id)}
29 <p>
30 <a
31 onclick={(e) => {
32 e.preventDefault()
33 setPostId(post.id)
34 }}
35 href="#{post.id}"
36 style={// We can use the queryCache here to show bold links for
37 // ones that are cached
38 queryClient.getQueryData([`/posts/${post.id}`])
39 ? 'font-weight: bold; color: green'
40 : ''}
41 >
42 {post.title}
43 </a>
44 </p>
45 {/each}
46 </div>
47 <div>{query.isFetching ? 'Background Updating...' : ' '}</div>
48 {/if}
49 </div>
50</div>