Open History to see the last commit
1import {
2 useMutation,
3 useQueryClient,
4 useSuspenseQuery,
5} from '@tanstack/preact-query'
6import { useState } from 'preact/hooks'
7import { todosMutations, todosQueries } from '../services/todos/queries'
8
9export default function TodoListUI() {
10 const queryClient = useQueryClient()
11 const [inputValue, setInputValue] = useState('')
12
13 const { data: todos } = useSuspenseQuery(todosQueries.list())
14
15 const addTodoMutation = useMutation({
16 ...todosMutations.create(),
17 onSettled: () =>
18 queryClient.invalidateQueries({ queryKey: todosQueries.list().queryKey }),
19 })
20
21 function handleSubmit(e: SubmitEvent) {
22 e.preventDefault()
23 const text = inputValue.trim()
24 if (!text) return
25 addTodoMutation.mutate(text)
26 setInputValue('')
27 }
28
29 return (
30 <div>
31 <p style={{ fontSize: '0.875rem', color: '#555', marginBottom: '1rem' }}>
32 <strong>Approach 1 — via UI variables:</strong> The pending item is
33 rendered directly from <code>mutation.variables</code>. No cache
34 manipulation needed. On error the pending item simply disappears.
35 </p>
36
37 <form
38 onSubmit={handleSubmit}
39 style={{ display: 'flex', gap: 8, marginBottom: '1rem' }}
40 >
41 <input
42 value={inputValue}
43 onInput={(e) => setInputValue(e.currentTarget.value)}
44 placeholder="New todo…"
45 style={{ flex: 1, padding: '0.4rem 0.6rem', fontSize: '1rem' }}
46 />
47 <button type="submit" disabled={addTodoMutation.isPending}>
48 Add
49 </button>
50 </form>
51
52 {addTodoMutation.isError && (
53 <p style={{ color: 'red', marginBottom: '0.5rem' }}>
54 {addTodoMutation.error.message}
55 </p>
56 )}
57
58 <ul style={{ listStyle: 'none', padding: 0 }}>
59 {todos.map((todo) => (
60 <li
61 key={todo.id}
62 style={{ padding: '0.4rem 0', borderBottom: '1px solid #eee' }}
63 >
64 {todo.text}
65 </li>
66 ))}
67 {addTodoMutation.isPending && (
68 <li
69 style={{
70 padding: '0.4rem 0',
71 borderBottom: '1px solid #eee',
72 opacity: 0.5,
73 }}
74 >
75 {addTodoMutation.variables} <em>(saving…)</em>
76 </li>
77 )}
78 </ul>
79 </div>
80 )
81}