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

EditTodo.svelte

96 lines2.4 KB

1<script lang="ts">
2 import {
3 useQueryClient,
4 createQuery,
5 createMutation,
6 } from '@tanstack/svelte-query'
7 import { editingIndex } from '$lib/stores.svelte'
8 import { todosMutations, todosQueries } from '$lib/services/todos/queries'
9 import type { Todo } from '$lib/services/todos/types'
10​
11 type Props = {
12 id: number
13 }
14​
15 let { id }: Props = $props()
16​
17 const queryClient = useQueryClient()
18​
19 const query = createQuery(() => todosQueries.detail(id))
20​
21 let draft = $state<Partial<Omit<Todo, 'id'>>>({})
22​
23 const saveMutation = createMutation(() => ({
24 ...todosMutations.update(),
25 onSuccess: (data) => {
26 // Update `todos` and the individual todo queries when this mutation succeeds
27 queryClient.invalidateQueries({ queryKey: todosQueries.lists() })
28 queryClient.setQueryData(todosQueries.detail(id).queryKey, data)
29 draft = {}
30 },
31 }))
32​
33 const disableEditSave = $derived(
34 query.status === 'pending' || saveMutation.status === 'pending',
35 )
36</script>
37​
38<div>
39 <div>
40 {#if query.data}
41 <button onclick={() => (editingIndex.value = null)}>Back</button> Editing
42 Todo "{query.data.name}" (#{id})
43 {/if}
44 </div>
45 {#if query.status === 'pending'}
46 <span>Loading... (Attempt: {query.failureCount + 1})</span>
47 {:else if query.error}
48 <span>
49 Error! <button onclick={() => query.refetch()}>Retry</button>
50 </span>
51 {:else if query.data}
52 {@const todo = query.data}
53 <label>
54 Name:
55 <input
56 value={draft.name ?? todo.name}
57 oninput={(e) => (draft.name = e.currentTarget.value)}
58 disabled={disableEditSave}
59 />
60 </label>
61 <label>
62 Notes:
63 <input
64 value={draft.notes ?? todo.notes}
65 oninput={(e) => (draft.notes = e.currentTarget.value)}
66 disabled={disableEditSave}
67 />
68 </label>
69 <div>
70 <button
71 onclick={() => saveMutation.mutate({ ...todo, ...draft })}
72 disabled={disableEditSave}
73 >
74 Save
75 </button>
76 </div>
77 <div>
78 {saveMutation.status === 'pending'
79 ? 'Saving...'
80 : saveMutation.status === 'error'
81 ? saveMutation.error.message
82 : saveMutation.status === 'success'
83 ? 'Saved!'
84 : null}
85 </div>
86 <div>
87 {#if query.isFetching}
88 <span>
89 Background Refreshing... (Attempt: {query.failureCount + 1})
90 </span>
91 {:else}
92 <span>&nbsp;</span>
93 {/if}
94 </div>
95 {/if}
96</div>