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

App.svelte

50 lines1.5 KB

1<script lang="ts">
2 import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query'
3 import { SvelteQueryDevtools } from '@tanstack/svelte-query-devtools'
4 import Post from './lib/Post.svelte'
5 import Posts from './lib/Posts.svelte'
6 import type { QueryKey } from '@tanstack/svelte-query'
7​
8 // Define a default query function that will receive the query key
9 const defaultQueryFn = async ({ queryKey }: { queryKey: QueryKey }) => {
10 const response = await fetch(
11 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
12 )
13 if (!response.ok) throw new Error('Failed to fetch data')
14 return await response.json()
15 }
16​
17 // provide the default query function to your app via the query client
18 const queryClient = new QueryClient({
19 defaultOptions: {
20 queries: {
21 queryFn: defaultQueryFn,
22 },
23 },
24 })
25​
26 let postId = $state(-1)
27​
28 const setPostId = (id: number) => {
29 postId = id
30 }
31</script>
32​
33<QueryClientProvider client={queryClient}>
34 <p>
35 As you visit the posts below, you will notice them in a loading state the
36 first time you load them. However, after you return to this list and click
37 on any posts you have already visited again, you will see them load
38 instantly and background refresh right before your eyes!
39 <strong>
40 (You may need to throttle your network speed to simulate longer loading
41 sequences)
42 </strong>
43 </p>
44 {#if postId > -1}
45 <Post {postId} {setPostId} />
46 {:else}
47 <Posts {setPostId} />
48 {/if}
49 <SvelteQueryDevtools initialIsOpen />
50</QueryClientProvider>