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

persisted-todos.ts

53 lines1.2 KB

1import { createCollection } from '@tanstack/react-db'
2import {
3 BrowserCollectionCoordinator,
4 createBrowserWASQLitePersistence,
5 openBrowserWASQLiteOPFSDatabase,
6 persistedCollectionOptions,
7} from '@tanstack/browser-db-sqlite-persistence'
8import type { Collection } from '@tanstack/db'
9​
10export type PersistedTodo = {
11 id: string
12 text: string
13 completed: boolean
14 createdAt: string
15 updatedAt: string
17​
18export type PersistedTodosHandle = {
19 collection: Collection<PersistedTodo, string>
20 close: () => Promise<void>
22​
23export async function createPersistedTodoCollection(): Promise<PersistedTodosHandle> {
24 const database = await openBrowserWASQLiteOPFSDatabase({
25 databaseName: `tanstack-db-demo-v2.sqlite`,
26 })
27​
28 const coordinator = new BrowserCollectionCoordinator({
29 dbName: `tanstack-db-demo`,
30 })
31​
32 const persistence = createBrowserWASQLitePersistence({
33 database,
34 coordinator,
35 })
36​
37 const collection = createCollection(
38 persistedCollectionOptions<PersistedTodo, string>({
39 id: `persisted-todos`,
40 getKey: (todo) => todo.id,
41 persistence,
42 schemaVersion: 1,
43 }),
44 )
45​
46 return {
47 collection: collection,
48 close: async () => {
49 coordinator.dispose()
50 await database.close?.()
51 },
52 }