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

EditTodo.svelte

138 lines3.7 KB

1<script lang="ts">
2 import {
3 useQueryClient,
4 createQuery,
5 createMutation,
6 } from '@tanstack/svelte-query'
7 import {
8 errorRate,
9 queryTimeMin,
10 queryTimeMax,
11 list,
12 editingIndex,
13 } from '$lib/stores.svelte'
14 import type { Todo } from '$lib/stores.svelte'
15​
16 const queryClient = useQueryClient()
17​
18 const fetchTodoById = async ({ id }: { id: number }): Promise<Todo> => {
19 return new Promise((resolve, reject) => {
20 setTimeout(
21 () => {
22 if (Math.random() < errorRate.value) {
23 return reject(
24 new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2)),
25 )
26 }
27 const todo = $state.snapshot(list.value.find((d) => d.id === id))
28 if (!todo) {
29 return reject(
30 new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2)),
31 )
32 }
33 resolve(todo)
34 },
35 queryTimeMin.value +
36 Math.random() * (queryTimeMax.value - queryTimeMin.value),
37 )
38 })
39 }
40​
41 function patchTodo(todo?: Todo): Promise<Todo> {
42 console.info('patchTodo', todo)
43 return new Promise((resolve, reject) => {
44 setTimeout(
45 () => {
46 if (Math.random() < errorRate.value) {
47 return reject(
48 new Error(JSON.stringify({ patchTodo: todo }, null, 2)),
49 )
50 }
51 if (!todo) {
52 return reject(
53 new Error(JSON.stringify({ patchTodo: todo }, null, 2)),
54 )
55 }
56 list.value = list.value.map((d) => {
57 if (d.id === todo.id) {
58 return $state.snapshot(todo)
59 }
60 return d
61 })
62 resolve(todo)
63 },
64 queryTimeMin.value +
65 Math.random() * (queryTimeMax.value - queryTimeMin.value),
66 )
67 })
68 }
69​
70 const query = createQuery(() => ({
71 queryKey: ['todo', { id: editingIndex.value }],
72 queryFn: () => fetchTodoById({ id: editingIndex.value || 0 }),
73 enabled: editingIndex.value !== null,
74 }))
75​
76 const saveMutation = createMutation(() => ({
77 mutationFn: patchTodo,
78 onSuccess: (data) => {
79 // Update `todos` and the individual todo queries when this mutation succeeds
80 queryClient.invalidateQueries({ queryKey: ['todos'] })
81 queryClient.setQueryData(['todo', { id: editingIndex }], data)
82 },
83 }))
84​
85 const todo = $derived(query.data)
86​
87 const onSave = () => {
88 saveMutation.mutate(todo)
89 }
90​
91 const disableEditSave = $derived(
92 query.status === 'pending' || saveMutation.status === 'pending',
93 )
94</script>
95​
96<div>
97 <div>
98 {#if query.data}
99 <button onclick={() => (editingIndex.value = null)}>Back</button> Editing
100 Todo "{query.data.name}" (#{editingIndex.value})
101 {/if}
102 </div>
103 {#if query.status === 'pending'}
104 <span>Loading... (Attempt: {query.failureCount + 1})</span>
105 {:else if query.error}
106 <span>
107 Error! <button onclick={() => query.refetch()}>Retry</button>
108 </span>
109 {:else if todo}
110 <label>
111 Name:{' '}
112 <input bind:value={todo.name} disabled={disableEditSave} />
113 </label>
114 <label>
115 Notes:{' '}
116 <input bind:value={todo.notes} disabled={disableEditSave} />
117 </label>
118 <div>
119 <button onclick={onSave} disabled={disableEditSave}> Save </button>
120 </div>
121 <div>
122 {saveMutation.status === 'pending'
123 ? 'Saving...'
124 : saveMutation.status === 'error'
125 ? saveMutation.error.message
126 : 'Saved!'}
127 </div>
128 <div>
129 {#if query.isFetching}
130 <span>
131 Background Refreshing... (Attempt: {query.failureCount + 1})
132 </span>
133 {:else}
134 <span>&nbsp;</span>
135 {/if}
136 </div>
137 {/if}
138</div>