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

+page.svelte

101 lines2.3 KB

1<script lang="ts">
2 import {
3 useQueryClient,
4 createQuery,
5 createMutation,
6 } from '@tanstack/svelte-query'
7​
8 let intervalMs = 1000
9 let value = ''
10​
11 const client = useQueryClient()
12​
13 const endpoint = 'http://localhost:5173/api/data'
14​
15 $: todos = createQuery<{ items: string[] }>({
16 queryKey: ['refetch'],
17 queryFn: async () => await fetch(endpoint).then((r) => r.json()),
18 // Refetch the data every second
19 refetchInterval: intervalMs,
20 })
21​
22 const addMutation = createMutation({
23 mutationFn: (value: string) =>
24 fetch(`${endpoint}?add=${value}`).then((r) => r.json()),
25 onSuccess: () => client.invalidateQueries({ queryKey: ['refetch'] }),
26 })
27​
28 const clearMutation = createMutation({
29 mutationFn: () => fetch(`${endpoint}?clear=1`).then((r) => r.json()),
30 onSuccess: () => client.invalidateQueries({ queryKey: ['refetch'] }),
31 })
32</script>
33​
34<h1>Auto Refetch with stale-time set to 1s</h1>
35​
36<p>
37 This example is best experienced on your own machine, where you can open
38 multiple tabs to the same localhost server and see your changes propagate
39 between the two.
40</p>
41​
42<label>
43 Query Interval speed (ms):{' '}
44 <div class="flex">
45 <input bind:value={intervalMs} type="number" step="100" />{' '}
46​
47 <span
48 style="display:inline-block;
49 margin-left:.5rem;
50 width:.75rem;
51 height:.75rem;
52 background: {$todos.isFetching ? 'green' : 'transparent'};
53 transition: {!$todos.isFetching ? 'all .3s ease' : 'none'};
54 border-radius: 100%;
55 transform: scale(1.5)"
56 ></span>
57 </div>
58</label>
59<h2>Todo List</h2>
60<form
61 on:submit={(e) => {
62 e.preventDefault()
63 e.stopPropagation()
64 $addMutation.mutate(value, {
65 onSuccess: () => (value = ''),
66 })
67 }}
69 <input placeholder="enter something" bind:value />
70</form>
71​
72{#if $todos.isPending}
73 Loading...
74{/if}
75{#if $todos.error}
76 An error has occurred:
77 {$todos.error.message}
78{/if}
79{#if $todos.isSuccess}
80 <ul>
81 {#each $todos.data.items as item}
82 <li>{item}</li>
83 {/each}
84 </ul>
85 <div>
86 <button on:click={() => $clearMutation.mutate(undefined)}>
87 Clear All
88 </button>
89 </div>
90{/if}
91{#if $todos.isFetching}
92 <div style="color:darkgreen; font-weight:700">
93 'Background Updating...' : ' '
94 </div>
95{/if}
96​
97<style>
98 li {
99 text-align: left;
100 }
101</style>