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

TodoList.tsx

193 lines5.5 KB

1import { useCallback, useEffect, useState } from 'react'
2import { useLiveQuery } from '@tanstack/react-db'
3import { createTodoActions } from '../db/todos'
4import { todoApi } from '../utils/api'
5import type { createTodos } from '../db/todos'
6​
7interface TodoListProps {
8 collection: ReturnType<typeof createTodos>['collection']
9 executor: ReturnType<typeof createTodos>['executor']
11​
12export function TodoList({ collection, executor }: TodoListProps) {
13 const [inputText, setInputText] = useState('')
14 const [isOnline, setIsOnline] = useState(navigator.onLine)
15 const [pendingCount, setPendingCount] = useState(0)
16 const [error, setError] = useState<string | null>(null)
17 const [actions] = useState(() => createTodoActions(executor))
18​
19 // Monitor network status
20 useEffect(() => {
21 const handleOnline = () => {
22 setIsOnline(true)
23 executor.notifyOnline()
24 }
25 const handleOffline = () => setIsOnline(false)
26​
27 window.addEventListener('online', handleOnline)
28 window.addEventListener('offline', handleOffline)
29 return () => {
30 window.removeEventListener('online', handleOnline)
31 window.removeEventListener('offline', handleOffline)
32 }
33 }, [executor])
34​
35 // Poll pending mutation count
36 useEffect(() => {
37 const interval = setInterval(() => {
38 setPendingCount(executor.getPendingCount())
39 }, 100)
40 return () => clearInterval(interval)
41 }, [executor])
42​
43 // Query all todos sorted by creation date
44 const { data: todos = [], isLoading } = useLiveQuery((query) =>
45 query
46 .from({ todo: collection })
47 .orderBy(({ todo }) => todo.createdAt, 'desc'),
48 )
49​
50 const handleAddTodo = useCallback(() => {
51 const text = inputText.trim()
52 if (!text) return
53 try {
54 setError(null)
55 actions.addTodo(text)
56 setInputText('')
57 } catch (err) {
58 setError(err instanceof Error ? err.message : 'Failed to add todo')
59 }
60 }, [inputText, actions])
61​
62 const handleKeyDown = useCallback(
63 (e: React.KeyboardEvent) => {
64 if (e.key === 'Enter') handleAddTodo()
65 },
66 [handleAddTodo],
67 )
68​
69 if (isLoading) {
70 return (
71 <div className="container">
72 <p>Loading...</p>
73 </div>
74 )
75 }
76​
77 return (
78 <div className="container">
79 <h1>TanStack DB – Electron Offline-First</h1>
80​
81 <div className="status-bar">
82 <span
83 className={`badge ${isOnline ? 'badge-online' : 'badge-offline'}`}
84 >
85 {isOnline ? 'Online' : 'Offline'}
86 </span>
87 <span
88 className={`badge ${executor.isOfflineEnabled ? 'badge-offline-enabled' : 'badge-offline-disabled'}`}
89 >
90 {executor.isOfflineEnabled ? 'Offline Mode' : 'Online Only'}
91 </span>
92 {pendingCount > 0 && (
93 <span className="badge badge-pending">{pendingCount} pending</span>
94 )}
95 <span className="badge badge-count">
96 {todos.length} todo{todos.length !== 1 ? 's' : ''}
97 </span>
98 <button
99 className="reset-btn"
100 onClick={async () => {
101 if (
102 !confirm(
103 'Reset everything? This clears all todos and local data.',
104 )
105 )
106 return
107 try {
108 await todoApi.deleteAll()
109 } catch {
110 // server may be offline — continue with local reset
111 }
112 await window.electronAPI.resetDatabase()
113 window.location.reload()
114 }}
115 >
116 Reset
117 </button>
118 </div>
119​
120 {error && (
121 <div className="error-bar">
122 <span>{error}</span>
123 <button onClick={() => setError(null)}>×</button>
124 </div>
125 )}
126​
127 <div className="input-row">
128 <input
129 type="text"
130 className="todo-input"
131 value={inputText}
132 onChange={(e) => setInputText(e.target.value)}
133 onKeyDown={handleKeyDown}
134 placeholder="What needs to be done?"
135 />
136 <button
137 className="add-btn"
138 onClick={handleAddTodo}
139 disabled={!inputText.trim()}
140 >
141 Add
142 </button>
143 </div>
144​
145 <ul className="todo-list">
146 {todos.map((todo) => (
147 <li
148 key={todo.id}
149 className={`todo-item ${todo.completed ? 'completed' : ''}`}
150 >
151 <button
152 className="toggle-btn"
153 onClick={() => actions.toggleTodo(todo.id)}
154 >
155 {todo.completed ? '✓' : '○'}
156 </button>
157 <span className="todo-text">{todo.text}</span>
158 <button
159 className="delete-btn"
160 onClick={() => actions.deleteTodo(todo.id)}
161 >
162 ×
163 </button>
164 </li>
165 ))}
166 </ul>
167​
168 {todos.length === 0 && (
169 <p className="empty-message">No todos yet. Add one above!</p>
170 )}
171​
172 <div className="instructions">
173 <h3>Try it out</h3>
174 <ul>
175 <li>
176 <strong>Persistence:</strong> Add todos, quit the app, reopen — data
177 is still there
178 </li>
179 <li>
180 <strong>Multiple windows:</strong> Press Cmd+N (or File → New
181 Window) to open a second window — each window syncs independently
182 with the server
183 </li>
184 <li>
185 <strong>Offline mode:</strong> Stop the server (
186 <code>pnpm dev:server</code>), add todos, restart — they sync
187 automatically
188 </li>
189 </ul>
190 </div>
191 </div>
192 )