Open History to see the last commit
1'use client'
2
3import React, { useState } from 'react'
4import { useQuery, useMutation, 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: () => {
38 void queryClient.invalidateQueries({ queryKey: ['todos'] })
39 },
40 })
41
42 function handleSubmit(e: React.FormEvent) {
43 e.preventDefault()
44 const text = inputValue.trim()
45 if (!text) return
46 addTodoMutation.mutate(text)
47 setInputValue('')
48 }
49
50 return (
51 <div>
52 <p style={{ fontSize: '0.875rem', color: '#555', marginBottom: '1rem' }}>
53 <strong>Approach 1 — via UI variables:</strong> The pending item is
54 rendered directly from <code>mutation.variables</code>. No cache
55 manipulation needed. On error the pending item simply disappears.
56 </p>
57
58 <form
59 onSubmit={handleSubmit}
60 style={{ display: 'flex', gap: 8, marginBottom: '1rem' }}
61 >
62 <input
63 value={inputValue}
64 onChange={(e) => setInputValue(e.target.value)}
65 placeholder="New todo…"
66 style={{ flex: 1, padding: '0.4rem 0.6rem', fontSize: '1rem' }}
67 />
68 <button type="submit" disabled={addTodoMutation.isPending}>
69 Add
70 </button>
71 </form>
72
73 {addTodoMutation.isError && (
74 <p style={{ color: 'red', marginBottom: '0.5rem' }}>
75 {addTodoMutation.error.message}
76 </p>
77 )}
78
79 <ul style={{ listStyle: 'none', padding: 0 }}>
80 {todos.map((todo) => (
81 <li
82 key={todo.id}
83 style={{ padding: '0.4rem 0', borderBottom: '1px solid #eee' }}
84 >
85 {todo.text}
86 </li>
87 ))}
88 {addTodoMutation.isPending && (
89 <li
90 style={{
91 padding: '0.4rem 0',
92 borderBottom: '1px solid #eee',
93 opacity: 0.5,
94 }}
95 >
96 {addTodoMutation.variables} <em>(saving…)</em>
97 </li>
98 )}
99 </ul>
100 </div>
101 )
102}