-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathAddTodo.svelte
67 lines (60 loc) · 1.61 KB
/
AddTodo.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<script lang="ts">
import { createMutation, useQueryClient } from '@tanstack/svelte-query'
import {
errorRate,
queryTimeMin,
queryTimeMax,
list,
id,
} from '$lib/stores.svelte'
import type { Todo } from '$lib/stores.svelte'
const queryClient = useQueryClient()
let name = $state('')
const postTodo = async ({ name, notes }: Omit<Todo, 'id'>) => {
return new Promise((resolve, reject) => {
setTimeout(
() => {
if (Math.random() < errorRate.value) {
return reject(
new Error(
JSON.stringify(
{ postTodo: { name: $state.snapshot(name), notes } },
null,
2,
),
),
)
}
const todo = { name, notes, id: id.value }
id.value = id.value + 1
list.value.push(todo)
resolve(todo)
},
queryTimeMin.value +
Math.random() * (queryTimeMax.value - queryTimeMin.value),
)
})
}
const addMutation = createMutation(() => ({
mutationFn: postTodo,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
}))
</script>
<div>
<input bind:value={name} disabled={addMutation.status === 'pending'} />
<button
onclick={() => addMutation.mutate({ name, notes: name })}
disabled={addMutation.status === 'pending' || !name}
>
Add Todo
</button>
<div>
{addMutation.status === 'pending'
? 'Saving...'
: addMutation.status === 'error'
? addMutation.error.message
: 'Saved!'}
</div>
</div>