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

AddTodo.svelte

61 lines1.4 KB

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