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