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