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