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 = 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 }}
68>
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>