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