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

AddTodo.svelte

55 lines1.4 KB

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