Open History to see the last commit
1<script lang="ts">
2 import '../app.css'
3 import {
4 useQueryClient,
5 createQuery,
6 createMutation,
7 } from '@tanstack/svelte-query'
8β
9 type Todo = {
10 id: string
11 text: string
12 }
13β
14 type Todos = {
15 items: readonly Todo[]
16 ts: number
17 }
18β
19 let text = $state<string>('')
20β
21 const client = useQueryClient()
22β
23 const endpoint = '/api/data'
24β
25 const fetchTodos = async (): Promise<Todos> =>
26 await fetch(endpoint).then((r) => r.json())
27β
28 const createTodo = async (text: string): Promise<Todo> =>
29 await fetch(endpoint, {
30 method: 'POST',
31 headers: {
32 'Content-Type': 'application/json',
33 },
34 body: JSON.stringify({
35 text,
36 }),
37 }).then((res) => res.json())
38β
39 const todos = createQuery<Todos>(() => ({
40 queryKey: ['optimistic'],
41 queryFn: fetchTodos,
42 }))
43β
44 const addTodoMutation = createMutation(() => ({
45 mutationFn: createTodo,
46 onMutate: async (newTodo: string) => {
47 text = ''
48 // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
49 await client.cancelQueries({ queryKey: ['optimistic'] })
50β
51 // Snapshot the previous value
52 const previousTodos = client.getQueryData<Todos>(['optimistic'])
53β
54 // Optimistically update to the new value
55 if (previousTodos) {
56 client.setQueryData<Todos>(['optimistic'], {
57 ...previousTodos,
58 items: [
59 ...previousTodos.items,
60 { id: Math.random().toString(), text: newTodo },
61 ],
62 })
63 }
64β
65 return { previousTodos }
66 },
67 // If the mutation fails, use the context returned from onMutate to roll back
68 onError: (err: any, variables: any, context: any) => {
69 if (context?.previousTodos) {
70 client.setQueryData<Todos>(['optimistic'], context.previousTodos)
71 }
72 },
73 // Always refetch after error or success:
74 onSettled: () => {
75 client.invalidateQueries({ queryKey: ['optimistic'] })
76 },
77 }))
78</script>
79β
80<h1>Optimistic Updates</h1>
81<p>
82 In this example, new items can be created using a mutation. The new item will
83 be optimistically added to the list in hopes that the server accepts the item.
84 If it does, the list is refetched with the true items from the list. Every now
85 and then, the mutation may fail though. When that happens, the previous list
86 of items is restored and the list is again refetched from the server.
87</p>
88β
89<form
90 onsubmit={(e) => {
91 e.preventDefault()
92 e.stopPropagation()
93 addTodoMutation.mutate(text)
94 }}
95>
96 <div>
97 <input type="text" bind:value={text} />
98 <button disabled={addTodoMutation.isPending}>Create</button>
99 </div>
100</form>
101β
102{#if todos.isPending}
103 Loading...
104{/if}
105{#if todos.error}
106 An error has occurred:
107 {todos.error.message}
108{/if}
109{#if todos.isSuccess}
110 <div class="mb-4">
111 Updated At: {new Date(todos.data.ts).toLocaleTimeString()}
112 </div>
113 <ul>
114 {#each todos.data.items as todo}
115 <li>{todo.text}</li>
116 {/each}
117 </ul>
118{/if}
119{#if todos.isFetching}
120 <div style="color:darkgreen; font-weight:700">
121 'Background Updating...' : ' '
122 </div>
123{/if}
124β
125<style>
126 li {
127 text-align: left;
128 }
129</style>