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

electric.tsx

81 lines2.2 KB

1import * as React from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { useLiveQuery } from '@tanstack/react-db'
4import {
5 electricConfigCollection,
6 electricTodoCollection,
7} from '../lib/collections'
8import { TodoApp } from '../components/TodoApp'
9import { api } from '../lib/api'
10import type { Transaction } from '@tanstack/react-db'
11​
12export const Route = createFileRoute(`/electric`)({
13 component: ElectricPage,
14 ssr: false,
15 loader: async () => {
16 await Promise.all([
17 electricTodoCollection.preload(),
18 electricConfigCollection.preload(),
19 ])
20​
21 return null
22 },
23})
24​
25function ElectricPage() {
26 // Get data using live queries with Electric collections
27 const { data: todos } = useLiveQuery((q) =>
28 q
29 .from({ todo: electricTodoCollection })
30 .orderBy(({ todo }) => todo.created_at, `asc`),
31 )
32​
33 const { data: configData } = useLiveQuery((q) =>
34 q.from({ config: electricConfigCollection }),
35 )
36​
37 // Electric collections use txid to track sync
38 const configMutationFn = async ({
39 transaction,
40 }: {
41 transaction: Transaction
42 }) => {
43 const txids: Array<number> = []
44​
45 // Handle inserts
46 const inserts = transaction.mutations.filter((m) => m.type === `insert`)
47 for (const mutation of inserts) {
48 const response = await api.config.create(mutation.modified)
49 txids.push(response.txid)
50 }
51​
52 // Handle updates
53 const updates = transaction.mutations.filter((m) => m.type === `update`)
54 for (const mutation of updates) {
55 if (!(`id` in mutation.original)) {
56 throw new Error(`Original config not found for update`)
57 }
58 const response = await api.config.update(
59 mutation.original.id,
60 mutation.changes,
61 )
62 txids.push(response.txid)
63 }
64​
65 // Wait for all txids to sync back to the collection
66 await Promise.all(
67 txids.map((txid) => electricConfigCollection.utils.awaitTxid(txid)),
68 )
69 }
70​
71 return (
72 <TodoApp
73 todos={todos}
74 configData={configData}
75 todoCollection={electricTodoCollection}
76 configCollection={electricConfigCollection}
77 title="todos (electric)"
78 configMutationFn={configMutationFn}
79 />
80 )