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
7interface MutationContext {
8 previousTodos: Array<Todo> | undefined
9 optimisticId: string
10}
11
12async function fetchTodos(): Promise<Array<Todo>> {
13 const res = await fetch('/api/todos')
14 if (!res.ok) throw new Error('Failed to fetch todos')
15 return res.json()
16}
17
18async function addTodo(text: string): Promise<Todo> {
19 const res = await fetch('/api/todos', {
20 method: 'POST',
21 headers: { 'Content-Type': 'application/json' },
22 body: JSON.stringify({ text }),
23 })
24 if (!res.ok) {
25 const err = (await res.json()) as { error: string }
26 throw new Error(err.error)
27 }
28 return res.json()
29}
30
31export default function TodoListCache() {
32 const queryClient = useQueryClient()
33 const [inputValue, setInputValue] = useState('')
34 const [lastError, setLastError] = useState<string | null>(null)
35
36 const { data: todos = [] } = useQuery({
37 queryKey: ['todos'],
38 queryFn: fetchTodos,
39 })
40
41 const addTodoMutation = useMutation<Todo, Error, string, MutationContext>({
42 mutationFn: addTodo,
43 onMutate: async (text) => {
44 setLastError(null)
45 await queryClient.cancelQueries({ queryKey: ['todos'] })
46
47 const previousTodos = queryClient.getQueryData<Array<Todo>>(['todos'])
48
49 const optimisticId = `optimistic-${Date.now()}`
50 const optimisticTodo: Todo = {
51 id: optimisticId,
52 text,
53 createdAt: Date.now(),
54 }
55
56 queryClient.setQueryData<Array<Todo>>(['todos'], (old = []) => [
57 ...old,
58 optimisticTodo,
59 ])
60
61 return { previousTodos, optimisticId }
62 },
63 onError: (_err, _text, context) => {
64 setLastError(_err.message)
65 if (context?.previousTodos !== undefined) {
66 queryClient.setQueryData(['todos'], context.previousTodos)
67 } else if (context?.optimisticId) {
68 queryClient.setQueryData<Array<Todo>>(['todos'], (old = []) =>
69 old.filter((todo) => todo.id !== context.optimisticId),
70 )
71 }
72 },
73 onSettled: () => {
74 void queryClient.invalidateQueries({ queryKey: ['todos'] })
75 },
76 })
77
78 function handleSubmit(e: React.FormEvent) {
79 e.preventDefault()
80 const text = inputValue.trim()
81 if (!text) return
82 addTodoMutation.mutate(text)
83 setInputValue('')
84 }
85
86 return (
87 <div>
88 <p style={{ fontSize: '0.875rem', color: '#555', marginBottom: '1rem' }}>
89 <strong>Approach 2 — via cache manipulation:</strong>{' '}
90 <code>onMutate</code> snapshots the cache and writes the optimistic item
91 in. <code>onError</code> restores the snapshot on failure.
92 </p>
93
94 <form
95 onSubmit={handleSubmit}
96 style={{ display: 'flex', gap: 8, marginBottom: '1rem' }}
97 >
98 <input
99 value={inputValue}
100 onChange={(e) => setInputValue(e.target.value)}
101 placeholder="New todo…"
102 style={{ flex: 1, padding: '0.4rem 0.6rem', fontSize: '1rem' }}
103 />
104 <button type="submit" disabled={addTodoMutation.isPending}>
105 Add
106 </button>
107 </form>
108
109 {lastError && (
110 <p style={{ color: 'red', marginBottom: '0.5rem' }}>{lastError}</p>
111 )}
112
113 <ul style={{ listStyle: 'none', padding: 0 }}>
114 {todos.map((todo) => (
115 <li
116 key={todo.id}
117 style={{
118 padding: '0.4rem 0',
119 borderBottom: '1px solid #eee',
120 opacity: todo.id.startsWith('optimistic-') ? 0.5 : 1,
121 }}
122 >
123 {todo.text}
124 {todo.id.startsWith('optimistic-') && <em> (saving…)</em>}
125 </li>
126 ))}
127 </ul>
128 </div>
129 )
130}