Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

TodoDemo.tsx

273 lines8.5 KB

1import React, { useEffect, useMemo, useState } from 'react'
2import { useLiveQuery } from '@tanstack/react-db'
3import { createTodoActions, todoCollection } from '~/db/todos'
4​
5interface TodoDemoProps {
6 title: string
7 description: string
8 storageType: `indexeddb` | `localstorage`
9 offline: any
11​
12export function TodoDemo({
13 title,
14 description,
15 storageType,
16 offline,
17}: TodoDemoProps) {
18 const [newTodoText, setNewTodoText] = useState(``)
19 const [error, setError] = useState<string | null>(null)
20 const [isOnline, setIsOnline] = useState(navigator.onLine)
21 const [pendingCount, setPendingCount] = useState(0)
22​
23 // Create actions based on offline executor
24 const actions = useMemo(() => createTodoActions(offline), [offline])
25 console.log({ offline, actions })
26​
27 // Use live query to get todos
28 const { data: todoList = [], isLoading } = useLiveQuery({
29 query: (q) =>
30 q
31 .from({ todo: todoCollection })
32 .orderBy(({ todo }) => todo.createdAt, `desc`),
33 })
34​
35 // Monitor online status
36 useEffect(() => {
37 const handleOnline = () => {
38 setIsOnline(true)
39 if (offline) {
40 offline.notifyOnline()
41 }
42 }
43 const handleOffline = () => setIsOnline(false)
44​
45 window.addEventListener(`online`, handleOnline)
46 window.addEventListener(`offline`, handleOffline)
47​
48 return () => {
49 window.removeEventListener(`online`, handleOnline)
50 window.removeEventListener(`offline`, handleOffline)
51 }
52 }, [offline])
53​
54 // Monitor pending transactions
55 useEffect(() => {
56 if (!offline) return
57​
58 const interval = setInterval(() => {
59 setPendingCount(offline.getPendingCount())
60 }, 100)
61​
62 return () => clearInterval(interval)
63 }, [offline])
64​
65 const handleAddTodo = async () => {
66 if (!newTodoText.trim()) return
67​
68 try {
69 setError(null)
70 if (typeof actions.addTodo === `function`) {
71 await actions.addTodo(newTodoText)
72 } else {
73 actions.addTodo(newTodoText)
74 }
75 setNewTodoText(``)
76 } catch (err) {
77 setError(err instanceof Error ? err.message : `Failed to add todo`)
78 }
79 }
80​
81 const handleToggleTodo = async (id: string) => {
82 try {
83 setError(null)
84 if (typeof actions.toggleTodo === `function`) {
85 await actions.toggleTodo(id)
86 } else {
87 actions.toggleTodo(id)
88 }
89 } catch (err) {
90 setError(err instanceof Error ? err.message : `Failed to toggle todo`)
91 }
92 }
93​
94 const handleDeleteTodo = async (id: string) => {
95 try {
96 setError(null)
97 if (typeof actions.deleteTodo === `function`) {
98 await actions.deleteTodo(id)
99 } else {
100 actions.deleteTodo(id)
101 }
102 } catch (err) {
103 setError(err instanceof Error ? err.message : `Failed to delete todo`)
104 }
105 }
106​
107 const handleKeyPress = (e: React.KeyboardEvent) => {
108 if (e.key === `Enter`) {
109 handleAddTodo()
110 }
111 }
112​
113 const getStorageIcon = () => {
114 switch (storageType) {
115 case `indexeddb`:
116 return `🗄️`
117 case `localstorage`:
118 return `💾`
119 default:
120 return `💿`
121 }
122 }
123​
124 return (
125 <div className="max-w-2xl mx-auto p-6">
126 <div className="bg-white rounded-lg shadow-lg p-6">
127 <div className="flex items-center gap-3 mb-4">
128 <span className="text-2xl">{getStorageIcon()}</span>
129 <div>
130 <h2 className="text-2xl font-bold text-gray-900">{title}</h2>
131 <p className="text-gray-600">{description}</p>
132 </div>
133 </div>
134​
135 {/* Status indicators */}
136 <div className="flex flex-wrap gap-4 mb-6 text-sm">
137 <div
138 className={`flex items-center gap-2 px-3 py-1 rounded-full ${
139 isOnline
140 ? `bg-green-100 text-green-800`
141 : `bg-red-100 text-red-800`
142 }`}
143 >
144 <div
145 className={`w-2 h-2 rounded-full ${
146 isOnline ? `bg-green-500` : `bg-red-500`
147 }`}
148 />
149 {isOnline ? `Online` : `Offline`}
150 </div>
151​
152 <div
153 className={`flex items-center gap-2 px-3 py-1 rounded-full ${
154 offline?.isOfflineEnabled
155 ? `bg-blue-100 text-blue-800`
156 : `bg-gray-100 text-gray-800`
157 }`}
158 >
159 <div
160 className={`w-2 h-2 rounded-full ${
161 offline?.isOfflineEnabled ? `bg-blue-500` : `bg-gray-500`
162 }`}
163 />
164 {offline?.isOfflineEnabled ? `Offline Mode Enabled` : `Online Only`}
165 </div>
166​
167 {pendingCount > 0 && (
168 <div className="flex items-center gap-2 px-3 py-1 rounded-full bg-yellow-100 text-yellow-800">
169 <div className="w-2 h-2 rounded-full bg-yellow-500 animate-pulse" />
170 {pendingCount} pending sync{pendingCount !== 1 ? `s` : ``}
171 </div>
172 )}
173 </div>
174​
175 {/* Error display */}
176 {error && (
177 <div className="mb-4 p-3 bg-red-100 border border-red-300 rounded-md">
178 <p className="text-red-700 text-sm">{error}</p>
179 </div>
180 )}
181​
182 {/* Add new todo */}
183 <div className="flex gap-2 mb-6">
184 <input
185 type="text"
186 value={newTodoText}
187 onChange={(e) => setNewTodoText(e.target.value)}
188 onKeyPress={handleKeyPress}
189 placeholder="Add a new todo..."
190 className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
191 disabled={isLoading}
192 />
193 <button
194 onClick={handleAddTodo}
195 disabled={isLoading || !newTodoText.trim()}
196 className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
197 >
198 Add
199 </button>
200 </div>
201​
202 {/* Todo list */}
203 <div className="space-y-2">
204 {isLoading && todoList.length === 0 ? (
205 <div className="text-center py-8 text-gray-500">
206 <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2" />
207 Loading todos...
208 </div>
209 ) : todoList.length === 0 ? (
210 <div className="text-center py-8 text-gray-500">
211 No todos yet. Add one above to get started!
212 <br />
213 <span className="text-xs">
214 Try going offline to see how it works
215 </span>
216 </div>
217 ) : (
218 todoList.map((todo) => {
219 return (
220 <div
221 key={todo.id}
222 className="flex items-center gap-3 p-3 border border-gray-200 rounded-md hover:bg-gray-50"
223 >
224 <button
225 onClick={() => handleToggleTodo(todo.id)}
226 className={`w-5 h-5 rounded border-2 flex items-center justify-center ${
227 todo.completed
228 ? `bg-green-500 border-green-500 text-white`
229 : `border-gray-300 hover:border-green-400`
230 }`}
231 >
232 {todo.completed && <span className="text-xs">✓</span>}
233 </button>
234 <span
235 className={`flex-1 ${
236 todo.completed
237 ? `line-through text-gray-500`
238 : `text-gray-900`
239 }`}
240 >
241 {todo.text}
242 </span>
243 <span className="text-xs text-gray-400">
244 {new Date(todo.createdAt).toLocaleDateString()}
245 </span>
246 <button
247 onClick={() => handleDeleteTodo(todo.id)}
248 className="px-2 py-1 text-red-600 hover:bg-red-50 rounded text-sm"
249 >
250 Delete
251 </button>
252 </div>
253 )
254 })
255 )}
256 </div>
257​
258 {/* Instructions */}
259 <div className="mt-6 p-4 bg-gray-50 rounded-md">
260 <h3 className="font-medium text-gray-900 mb-2">Try this:</h3>
261 <ol className="text-sm text-gray-600 space-y-1">
262 <li>1. Add some todos while online</li>
263 <li>3. Add more todos (they'll be stored locally)</li>
264 <li>4. Go back online to see them sync</li>
265 <li>
266 5. Open this page in another tab to test multi-tab coordination
267 </li>
268 </ol>
269 </div>
270 </div>
271 </div>
272 )