Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

index.tsx

74 lines2.6 KB

1import { createCollection, useLiveQuery } from '@tanstack/react-db'
2import { electricCollectionOptions } from '@tanstack/electric-db-collection'
3import { useState } from 'react'
4import { options, type Item } from '../shared'
5​
6export const collection = createCollection(
7 electricCollectionOptions<Item>({
8 id: 'electric-items',
9 shapeOptions: options,
10 getKey: (row) => row.id,
11 syncMode: 'eager',
12 onUpdate: async ({ transaction, collection }) => {
13 const mutation = transaction.mutations[0]
14 const response = await fetch('/api/items', {
15 method: 'POST',
16 headers: { 'content-type': 'application/json' },
17 body: JSON.stringify({ id: mutation.original.id, ...mutation.changes }),
18 })
19 if (!response.ok) throw new Error('Mutation failed')
20 const { txid } = (await response.json()) as { txid: number }
21 await collection.utils.awaitTxId(txid, 15_000)
22 },
23 })
25export function TanStack() {
26 const { data, isLoading } = useLiveQuery((q) => q.from({ items: collection }))
27 const [state, setState] = useState('idle')
28 return (
29 <>
30 <pre data-testid="rows" data-loading={isLoading}>
31 {JSON.stringify(data)}
32 </pre>
33 <button
34 onClick={() => {
35 const requested = new URLSearchParams(location.search).get('item')
36 const row = requested
37 ? data.find((row) => row.id === Number(requested))
38 : data[0]
39 if (!row) return
40 setState('pending')
41 const tx = collection.update(row.id, (draft) => {
42 draft.label = 'optimistic'
43 })
44 void tx.isPersisted.promise.then(
45 () => setState('persisted'),
46 () => setState('failed')
47 )
48 }}
49 >
50 Update first row
51 </button>
52 <output data-testid="mutation">{state}</output>
53 <button
54 onClick={() => {
55 const id = Number(new URLSearchParams(location.search).get('item'))
56 setState('pending')
57 void (async () => {
58 const response = await fetch('/api/items', {
59 method: 'POST',
60 headers: { 'content-type': 'application/json' },
61 body: JSON.stringify({ id, noop: true }),
62 })
63 if (!response.ok) throw new Error('Mutation failed')
64 const { txid } = (await response.json()) as { txid: number }
65 await collection.utils.awaitTxId(txid, 15_000)
66 setState('acknowledged')
67 })().catch(() => setState('failed'))
68 }}
69 >
70 Acknowledge unchanged row
71 </button>
72 </>
73 )