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

wa-sqlite.tsx

95 lines2.9 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { useEffect, useState } from 'react'
3import type { PersistedTodosHandle } from '~/db/persisted-todos'
4import { PersistedTodoDemo } from '~/components/PersistedTodoDemo'
5import { createPersistedTodoCollection } from '~/db/persisted-todos'
6​
7export const Route = createFileRoute(`/wa-sqlite`)({
8 component: WASQLiteDemo,
9})
10​
11function WASQLiteDemo() {
12 const [handle, setHandle] = useState<PersistedTodosHandle | null>(null)
13 const [error, setError] = useState<string | null>(null)
14​
15 useEffect(() => {
16 let disposed = false
17 let currentHandle: PersistedTodosHandle | null = null
18​
19 createPersistedTodoCollection()
20 .then((h) => {
21 if (disposed) {
22 h.close()
23 return
24 }
25 currentHandle = h
26 setHandle(h)
27 })
28 .catch((err) => {
29 if (!disposed) {
30 console.error(`Failed to initialize wa-sqlite persistence:`, err)
31 setError(
32 err instanceof Error
33 ? err.message
34 : `Failed to initialize persistence`,
35 )
36 }
37 })
38​
39 return () => {
40 disposed = true
41 currentHandle?.close()
42 }
43 }, [])
44​
45 if (error) {
46 return (
47 <div className="min-h-screen bg-gray-100 py-8">
48 <div className="max-w-2xl mx-auto p-6">
49 <div className="bg-white rounded-lg shadow-lg p-6">
50 <div className="flex items-center gap-3 mb-4">
51 <span className="text-2xl">⚠️</span>
52 <div>
53 <h2 className="text-2xl font-bold text-gray-900">
54 Persistence Unavailable
55 </h2>
56 <p className="text-gray-600">
57 wa-sqlite OPFS persistence could not be initialized.
58 </p>
59 </div>
60 </div>
61 <div className="p-3 bg-red-100 border border-red-300 rounded-md">
62 <p className="text-red-700 text-sm">{error}</p>
63 </div>
64 <p className="mt-4 text-sm text-gray-500">
65 This feature requires a browser with OPFS support (Chrome 102+,
66 Edge 102+, Firefox 111+, Safari 15.2+) and a secure context (HTTPS
67 or localhost).
68 </p>
69 </div>
70 </div>
71 </div>
72 )
73 }
74​
75 if (!handle) {
76 return (
77 <div className="min-h-screen bg-gray-100 py-8">
78 <div className="max-w-2xl mx-auto p-6">
79 <div className="bg-white rounded-lg shadow-lg p-6 text-center">
80 <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2" />
81 <p className="text-gray-600">
82 Initializing wa-sqlite persistence...
83 </p>
84 </div>
85 </div>
86 </div>
87 )
88 }
89​
90 return (
91 <div className="min-h-screen bg-gray-100 py-8">
92 <PersistedTodoDemo collection={handle.collection} />
93 </div>
94 )