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

TodoListCache.tsx

117 lines3.4 KB

1import { useState } from 'preact/hooks'
2import {
3 useMutation,
4 useQueryClient,
5 useSuspenseQuery,
6} from '@tanstack/preact-query'
7import { todosMutations, todosQueries } from '../services/todos/queries'
8import type { Todo } from '../services/todos/types'
9​
10interface MutationContext {
11 previousTodos: Array<Todo> | undefined
12 optimisticId: string
14​
15export default function TodoListCache() {
16 const queryClient = useQueryClient()
17 const [inputValue, setInputValue] = useState('')
18 const [lastError, setLastError] = useState<string | null>(null)
19​
20 const { data: todos } = useSuspenseQuery(todosQueries.list())
21​
22 const addTodoMutation = useMutation<Todo, Error, string, MutationContext>({
23 ...todosMutations.create(),
24 onMutate: async (text) => {
25 setLastError(null)
26 await queryClient.cancelQueries({
27 queryKey: todosQueries.list().queryKey,
28 })
29​
30 const previousTodos = queryClient.getQueryData(
31 todosQueries.list().queryKey,
32 )
33​
34 const optimisticId = `optimistic-${Date.now()}`
35 const optimisticTodo: Todo = {
36 id: optimisticId,
37 text,
38 createdAt: Date.now(),
39 }
40​
41 queryClient.setQueryData(todosQueries.list().queryKey, (old = []) => [
42 ...old,
43 optimisticTodo,
44 ])
45​
46 return { previousTodos, optimisticId }
47 },
48 onError: (_err, _text, context) => {
49 setLastError(_err.message)
50 if (context?.previousTodos !== undefined) {
51 queryClient.setQueryData(
52 todosQueries.list().queryKey,
53 context.previousTodos,
54 )
55 } else if (context?.optimisticId) {
56 queryClient.setQueryData(todosQueries.list().queryKey, (old = []) =>
57 old.filter((todo) => todo.id !== context.optimisticId),
58 )
59 }
60 },
61 onSettled: () =>
62 queryClient.invalidateQueries({ queryKey: todosQueries.list().queryKey }),
63 })
64​
65 function handleSubmit(e: SubmitEvent) {
66 e.preventDefault()
67 const text = inputValue.trim()
68 if (!text) return
69 addTodoMutation.mutate(text)
70 setInputValue('')
71 }
72​
73 return (
74 <div>
75 <p style={{ fontSize: '0.875rem', color: '#555', marginBottom: '1rem' }}>
76 <strong>Approach 2 — via cache manipulation:</strong>{' '}
77 <code>onMutate</code> snapshots the cache and writes the optimistic item
78 in. <code>onError</code> restores the snapshot on failure.
79 </p>
80​
81 <form
82 onSubmit={handleSubmit}
83 style={{ display: 'flex', gap: 8, marginBottom: '1rem' }}
84 >
85 <input
86 value={inputValue}
87 onInput={(e) => setInputValue(e.currentTarget.value)}
88 placeholder="New todo…"
89 style={{ flex: 1, padding: '0.4rem 0.6rem', fontSize: '1rem' }}
90 />
91 <button type="submit" disabled={addTodoMutation.isPending}>
92 Add
93 </button>
94 </form>
95​
96 {lastError && (
97 <p style={{ color: 'red', marginBottom: '0.5rem' }}>{lastError}</p>
98 )}
99​
100 <ul style={{ listStyle: 'none', padding: 0 }}>
101 {todos.map((todo) => (
102 <li
103 key={todo.id}
104 style={{
105 padding: '0.4rem 0',
106 borderBottom: '1px solid #eee',
107 opacity: todo.id.startsWith('optimistic-') ? 0.5 : 1,
108 }}
109 >
110 {todo.text}
111 {todo.id.startsWith('optimistic-') && <em> (saving…)</em>}
112 </li>
113 ))}
114 </ul>
115 </div>
116 )