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