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

PersistedTodoDemo.tsx

184 lines6.1 KB

1import React, { useState } from 'react'
2import { useLiveQuery } from '@tanstack/react-db'
3import type { Collection } from '@tanstack/db'
4import type { PersistedTodo } from '~/db/persisted-todos'
5​
6interface PersistedTodoDemoProps {
7 collection: Collection<PersistedTodo, string>
8}
9​
10export function PersistedTodoDemo({ collection }: PersistedTodoDemoProps) {
11 const [newTodoText, setNewTodoText] = useState(``)
12 const [error, setError] = useState<string | null>(null)
13​
14 const { data: todoList = [] } = useLiveQuery({
15 query: (q) =>
16 q
17 .from({ todo: collection })
18 .orderBy(({ todo }) => todo.createdAt, `desc`),
19 })
20​
21 const handleAddTodo = () => {
22 if (!newTodoText.trim()) return
23​
24 try {
25 setError(null)
26 const now = new Date().toISOString()
27 collection.insert({
28 id: crypto.randomUUID(),
29 text: newTodoText.trim(),
30 completed: false,
31 createdAt: now,
32 updatedAt: now,
33 })
34 setNewTodoText(``)
35 } catch (err) {
36 setError(err instanceof Error ? err.message : `Failed to add todo`)
37 }
38 }
39​
40 const handleToggleTodo = (id: string) => {
41 try {
42 setError(null)
43 collection.update(id, (draft) => {
44 draft.completed = !draft.completed
45 draft.updatedAt = new Date().toISOString()
46 })
47 } catch (err) {
48 setError(err instanceof Error ? err.message : `Failed to toggle todo`)
49 }
50 }
51​
52 const handleDeleteTodo = (id: string) => {
53 try {
54 setError(null)
55 collection.delete(id)
56 } catch (err) {
57 setError(err instanceof Error ? err.message : `Failed to delete todo`)
58 }
59 }
60​
61 const handleKeyPress = (e: React.KeyboardEvent) => {
62 if (e.key === `Enter`) {
63 handleAddTodo()
64 }
65 }
66​
67 return (
68 <div className="max-w-2xl mx-auto p-6">
69 <div className="bg-white rounded-lg shadow-lg p-6">
70 <div className="flex items-center gap-3 mb-4">
71 <span className="text-2xl">🗃️</span>
72 <div>
73 <h2 className="text-2xl font-bold text-gray-900">
74 wa-sqlite OPFS Persistence Demo
75 </h2>
76 <p className="text-gray-600">
77 Collection data is persisted to SQLite via OPFS. Data survives
78 page reloads without any server sync.
79 </p>
80 </div>
81 </div>
82​
83 {/* Persistence indicator */}
84 <div className="flex flex-wrap gap-4 mb-6 text-sm">
85 <div className="flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-100 text-emerald-800">
86 <div className="w-2 h-2 rounded-full bg-emerald-500" />
87 SQLite OPFS Persistence Active
88 </div>
89 <div className="flex items-center gap-2 px-3 py-1 rounded-full bg-gray-100 text-gray-600">
90 {todoList.length} todo{todoList.length !== 1 ? `s` : ``}
91 </div>
92 </div>
93​
94 {/* Error display */}
95 {error && (
96 <div className="mb-4 p-3 bg-red-100 border border-red-300 rounded-md">
97 <p className="text-red-700 text-sm">{error}</p>
98 </div>
99 )}
100​
101 {/* Add new todo */}
102 <div className="flex gap-2 mb-6">
103 <input
104 type="text"
105 value={newTodoText}
106 onChange={(e) => setNewTodoText(e.target.value)}
107 onKeyPress={handleKeyPress}
108 placeholder="Add a new todo..."
109 className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
110 />
111 <button
112 onClick={handleAddTodo}
113 disabled={!newTodoText.trim()}
114 className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
115 >
116 Add
117 </button>
118 </div>
119​
120 {/* Todo list */}
121 <div className="space-y-2">
122 {todoList.length === 0 ? (
123 <div className="text-center py-8 text-gray-500">
124 No todos yet. Add one above to get started!
125 <br />
126 <span className="text-xs">
127 Try adding todos, then refresh the page to see them persist
128 </span>
129 </div>
130 ) : (
131 todoList.map((todo) => (
132 <div
133 key={todo.id}
134 className="flex items-center gap-3 p-3 border border-gray-200 rounded-md hover:bg-gray-50"
135 >
136 <button
137 onClick={() => handleToggleTodo(todo.id)}
138 className={`w-5 h-5 rounded border-2 flex items-center justify-center ${
139 todo.completed
140 ? `bg-green-500 border-green-500 text-white`
141 : `border-gray-300 hover:border-green-400`
142 }`}
143 >
144 {todo.completed && <span className="text-xs">✓</span>}
145 </button>
146 <span
147 className={`flex-1 ${
148 todo.completed
149 ? `line-through text-gray-500`
150 : `text-gray-900`
151 }`}
152 >
153 {todo.text}
154 </span>
155 <span className="text-xs text-gray-400">
156 {new Date(todo.createdAt).toLocaleDateString()}
157 </span>
158 <button
159 onClick={() => handleDeleteTodo(todo.id)}
160 className="px-2 py-1 text-red-600 hover:bg-red-50 rounded text-sm"
161 >
162 Delete
163 </button>
164 </div>
165 ))
166 )}
167 </div>
168​
169 {/* Instructions */}
170 <div className="mt-6 p-4 bg-gray-50 rounded-md">
171 <h3 className="font-medium text-gray-900 mb-2">Try this:</h3>
172 <ol className="text-sm text-gray-600 space-y-1">
173 <li>1. Add some todos</li>
174 <li>2. Refresh the page (Ctrl+R / Cmd+R)</li>
175 <li>
176 3. Your todos are still here - persisted in SQLite via OPFS!
177 </li>
178 <li>4. This uses wa-sqlite with OPFSCoopSyncVFS in a Web Worker</li>
179 </ol>
180 </div>
181 </div>
182 </div>
183 )