Open History to see the last commit
1'use client'
2
3import React, { useState } from 'react'
4import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
5import type { Todo } from '@/app/api/todos/data'
6
7async function fetchTodos(): Promise<Array<Todo>> {
8 const res = await fetch('/api/todos')
9 if (!res.ok) throw new Error('Failed to fetch todos')
10 return res.json()
11}
12
13async function addTodo(text: string): Promise<Todo> {
14 const res = await fetch('/api/todos', {
15 method: 'POST',
16 headers: { 'Content-Type': 'application/json' },
17 body: JSON.stringify({ text }),
18 })
19 if (!res.ok) {
20 const err = (await res.json()) as { error: string }
21 throw new Error(err.error)
22 }
23 return res.json()
24}
25
26export default function TodoListUI() {
27 const queryClient = useQueryClient()
28 const [inputValue, setInputValue] = useState('')
29
30 const { data: todos = [] } = useQuery({
31 queryKey: ['todos'],
32 queryFn: fetchTodos,
33 })
34
35 const addTodoMutation = useMutation({
36 mutationFn: addTodo,
37 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
38 })
39
40 function handleSubmit(e: React.FormEvent) {
41 e.preventDefault()
42 const text = inputValue.trim()
43 if (!text) return
44 addTodoMutation.mutate(text)
45 setInputValue('')
46 }
47
48 return (
49 <div>
50 <p style={{ fontSize: '0.875rem', color: '#555', marginBottom: '1rem' }}>
51 <strong>Approach 1 — via UI variables:</strong> The pending item is
52 rendered directly from <code>mutation.variables</code>. No cache
53 manipulation needed. On error the pending item simply disappears.
54 </p>
55
56 <form
57 onSubmit={handleSubmit}
58 style={{ display: 'flex', gap: 8, marginBottom: '1rem' }}
59 >
60 <input
61 value={inputValue}
62 onChange={(e) => setInputValue(e.target.value)}
63 placeholder="New todo…"
64 style={{ flex: 1, padding: '0.4rem 0.6rem', fontSize: '1rem' }}
65 />
66 <button type="submit" disabled={addTodoMutation.isPending}>
67 Add
68 </button>
69 </form>
70
71 {addTodoMutation.isError && (
72 <p style={{ color: 'red', marginBottom: '0.5rem' }}>
73 {addTodoMutation.error.message}
74 </p>
75 )}
76
77 <ul style={{ listStyle: 'none', padding: 0 }}>
78 {todos.map((todo) => (
79 <li
80 key={todo.id}
81 style={{ padding: '0.4rem 0', borderBottom: '1px solid #eee' }}
82 >
83 {todo.text}
84 </li>
85 ))}
86 {addTodoMutation.isPending && (
87 <li
88 style={{
89 padding: '0.4rem 0',
90 borderBottom: '1px solid #eee',
91 opacity: 0.5,
92 }}
93 >
94 {addTodoMutation.variables} <em>(saving…)</em>
95 </li>
96 )}
97 </ul>
98 </div>
99 )
100}