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