Open History to see the last commit
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({
28 query: (q) =>
29 q
30 .from({ todo: electricTodoCollection })
31 .orderBy(({ todo }) => todo.created_at, `asc`),
32 })
33
34 const { data: configData } = useLiveQuery({
35 query: (q) => q.from({ config: electricConfigCollection }),
36 })
37
38 // Electric collections use txid to track sync
39 const configMutationFn = async ({
40 transaction,
41 }: {
42 transaction: Transaction
43 }) => {
44 const txids: Array<number> = []
45
46 // Handle inserts
47 const inserts = transaction.mutations.filter((m) => m.type === `insert`)
48 for (const mutation of inserts) {
49 const response = await api.config.create(mutation.modified)
50 txids.push(response.txid)
51 }
52
53 // Handle updates
54 const updates = transaction.mutations.filter((m) => m.type === `update`)
55 for (const mutation of updates) {
56 if (!(`id` in mutation.original)) {
57 throw new Error(`Original config not found for update`)
58 }
59 const response = await api.config.update(
60 mutation.original.id,
61 mutation.changes,
62 )
63 txids.push(response.txid)
64 }
65
66 // Wait for all txids to sync back to the collection
67 await Promise.all(
68 txids.map((txid) => electricConfigCollection.utils.awaitTxid(txid)),
69 )
70 }
71
72 return (
73 <TodoApp
74 todos={todos}
75 configData={configData}
76 todoCollection={electricTodoCollection}
77 configCollection={electricConfigCollection}
78 title="todos (electric)"
79 configMutationFn={configMutationFn}
80 />
81 )
82}