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