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

ElectricCollectionConfig.md

304 lines9.0 KB

1---
2id: ElectricCollectionConfig
3title: ElectricCollectionConfig
4---
5​
6Defined in: [packages/electric-db-collection/src/electric.ts:342](https://github.com/TanStack/db/blob/main/packages/electric-db-collection/src/electric.ts#L342)
7​
8Configuration interface for Electric collection options
9​
10## Extends
11​
12- `Omit`\<`BaseCollectionConfig`\<`T`, `string` \| `number`, `TSchema`, [`ElectricCollectionUtils`](ElectricCollectionUtils.md)\<`T`\>\>, `"onInsert"` \| `"onUpdate"` \| `"onDelete"` \| `"syncMode"`\>
13​
14## Type Parameters
15​
16### T
17​
18`T` *extends* `Row`\<`unknown`\> = `Row`\<`unknown`\>
19​
20The type of items in the collection
21​
22### TSchema
23​
24`TSchema` *extends* `StandardSchemaV1` = `never`
25​
26The schema type for validation
27​
28## Properties
29​
30### \[ELECTRIC\_TEST\_HOOKS\]?
31​
32```ts
33optional [ELECTRIC_TEST_HOOKS]: ElectricTestHooks;
34```
35​
36Defined in: [packages/electric-db-collection/src/electric.ts:359](https://github.com/TanStack/db/blob/main/packages/electric-db-collection/src/electric.ts#L359)
37​
38Internal test hooks (for testing only)
39Hidden via Symbol to prevent accidental usage in production
40​
41***
42​
43### onDelete()?
44​
45```ts
46optional onDelete: (params) => Promise<MatchingStrategy>;
47```
48​
49Defined in: [packages/electric-db-collection/src/electric.ts:545](https://github.com/TanStack/db/blob/main/packages/electric-db-collection/src/electric.ts#L545)
50​
51Optional asynchronous handler function called before a delete operation
52​
53**IMPORTANT - Electric Synchronization:**
54This handler **must not resolve** until synchronization is confirmed.
55Await one of these synchronization utilities before the handler completes:
561. `await collection.utils.awaitTxId(txid)` (recommended for most cases)
572. `await collection.utils.awaitMatch(fn)` for custom matching logic
58​
59Simply returning without waiting for sync will drop optimistic state too early, causing UI glitches.
60​
61#### Parameters
62​
63##### params
64​
65`DeleteMutationFnParams`\<`T`, `string` \| `number`, [`ElectricCollectionUtils`](ElectricCollectionUtils.md)\<`T`\>\>
66​
67Object containing transaction and collection information
68​
69#### Returns
70​
71`Promise`\<`MatchingStrategy`\>
72​
73Promise that should resolve after synchronization is complete
74​
75**Deprecation notice:** Returning `{ txid }` from handlers is deprecated and will be removed in v1.0.
76Use `await collection.utils.awaitTxId(txid)` within the handler instead.
77​
78#### Examples
79​
80```ts
81// Recommended: Wait for txid to sync
82onDelete: async ({ transaction, collection }) => {
83 const mutation = transaction.mutations[0]
84 const result = await api.todos.delete({
85 id: mutation.original.id
86 })
87 // Wait for txid to sync before handler completes
88 await collection.utils.awaitTxId(result.txid)
90```
91​
92```ts
93// Alternative: Use awaitMatch utility for custom matching logic
94onDelete: async ({ transaction, collection }) => {
95 const mutation = transaction.mutations[0]
96 await api.todos.delete({ id: mutation.original.id })
97 // Wait for specific change to appear in sync stream
98 await collection.utils.awaitMatch(
99 (message) => isChangeMessage(message) &&
100 message.headers.operation === 'delete' &&
101 message.value.id === mutation.original.id
102 )
104```
105​
106***
107​
108### onInsert()?
109​
110```ts
111optional onInsert: (params) => Promise<MatchingStrategy>;
112```
113​
114Defined in: [packages/electric-db-collection/src/electric.ts:446](https://github.com/TanStack/db/blob/main/packages/electric-db-collection/src/electric.ts#L446)
115​
116Optional asynchronous handler function called before an insert operation
117​
118**IMPORTANT - Electric Synchronization:**
119This handler **must not resolve** until synchronization is confirmed.
120Await one of these synchronization utilities before the handler completes:
1211. `await collection.utils.awaitTxId(txid)` (recommended for most cases)
1222. `await collection.utils.awaitMatch(fn)` for custom matching logic
123​
124Simply returning without waiting for sync will drop optimistic state too early, causing UI glitches.
125​
126#### Parameters
127​
128##### params
129​
130`InsertMutationFnParams`\<`T`, `string` \| `number`, [`ElectricCollectionUtils`](ElectricCollectionUtils.md)\<`T`\>\>
131​
132Object containing transaction and collection information
133​
134#### Returns
135​
136`Promise`\<`MatchingStrategy`\>
137​
138Promise that should resolve after synchronization is complete
139​
140**Deprecation notice:** Returning `{ txid }` from handlers is deprecated and will be removed in v1.0.
141Use `await collection.utils.awaitTxId(txid)` within the handler instead.
142​
143#### Examples
144​
145```ts
146// Recommended: Wait for txid to sync
147onInsert: async ({ transaction, collection }) => {
148 const newItem = transaction.mutations[0].modified
149 const result = await api.todos.create({
150 data: newItem
151 })
152 // Wait for txid to sync before handler completes
153 await collection.utils.awaitTxId(result.txid)
155```
156​
157```ts
158// Insert handler with custom timeout
159onInsert: async ({ transaction, collection }) => {
160 const newItem = transaction.mutations[0].modified
161 const result = await api.todos.create({
162 data: newItem
163 })
164 // Wait up to 10 seconds for txid
165 await collection.utils.awaitTxId(result.txid, 10000)
167```
168​
169```ts
170// Insert handler with timeout error handling
171onInsert: async ({ transaction, collection }) => {
172 const newItem = transaction.mutations[0].modified
173 const result = await api.todos.create({
174 data: newItem
175 })
176​
177 try {
178 await collection.utils.awaitTxId(result.txid, 5000)
179 } catch (error) {
180 // Decide sync timeout policy:
181 // - Throw to rollback optimistic state
182 // - Catch to keep optimistic state (eventual consistency)
183 // - Schedule background retry
184 console.warn('Sync timeout, keeping optimistic state:', error)
185 // Don't throw - allow optimistic state to persist
186 }
188```
189​
190```ts
191// Insert handler with multiple items
192onInsert: async ({ transaction, collection }) => {
193 const items = transaction.mutations.map(m => m.modified)
194 const results = await Promise.all(
195 items.map(item => api.todos.create({ data: item }))
196 )
197 // Wait for all txids to sync
198 await Promise.all(
199 results.map(r => collection.utils.awaitTxId(r.txid))
200 )
202```
203​
204```ts
205// Alternative: Use awaitMatch utility for custom matching logic
206onInsert: async ({ transaction, collection }) => {
207 const newItem = transaction.mutations[0].modified
208 await api.todos.create({ data: newItem })
209 // Wait for specific change to appear in sync stream
210 await collection.utils.awaitMatch(
211 (message) => isChangeMessage(message) &&
212 message.headers.operation === 'insert' &&
213 message.value.name === newItem.name
214 )
216```
217​
218***
219​
220### onUpdate()?
221​
222```ts
223optional onUpdate: (params) => Promise<MatchingStrategy>;
224```
225​
226Defined in: [packages/electric-db-collection/src/electric.ts:496](https://github.com/TanStack/db/blob/main/packages/electric-db-collection/src/electric.ts#L496)
227​
228Optional asynchronous handler function called before an update operation
229​
230**IMPORTANT - Electric Synchronization:**
231This handler **must not resolve** until synchronization is confirmed.
232Await one of these synchronization utilities before the handler completes:
2331. `await collection.utils.awaitTxId(txid)` (recommended for most cases)
2342. `await collection.utils.awaitMatch(fn)` for custom matching logic
235​
236Simply returning without waiting for sync will drop optimistic state too early, causing UI glitches.
237​
238#### Parameters
239​
240##### params
241​
242`UpdateMutationFnParams`\<`T`, `string` \| `number`, [`ElectricCollectionUtils`](ElectricCollectionUtils.md)\<`T`\>\>
243​
244Object containing transaction and collection information
245​
246#### Returns
247​
248`Promise`\<`MatchingStrategy`\>
249​
250Promise that should resolve after synchronization is complete
251​
252**Deprecation notice:** Returning `{ txid }` from handlers is deprecated and will be removed in v1.0.
253Use `await collection.utils.awaitTxId(txid)` within the handler instead.
254​
255#### Examples
256​
257```ts
258// Recommended: Wait for txid to sync
259onUpdate: async ({ transaction, collection }) => {
260 const { original, changes } = transaction.mutations[0]
261 const result = await api.todos.update({
262 where: { id: original.id },
263 data: changes
264 })
265 // Wait for txid to sync before handler completes
266 await collection.utils.awaitTxId(result.txid)
268```
269​
270```ts
271// Alternative: Use awaitMatch utility for custom matching logic
272onUpdate: async ({ transaction, collection }) => {
273 const { original, changes } = transaction.mutations[0]
274 await api.todos.update({ where: { id: original.id }, data: changes })
275 // Wait for specific change to appear in sync stream
276 await collection.utils.awaitMatch(
277 (message) => isChangeMessage(message) &&
278 message.headers.operation === 'update' &&
279 message.value.id === original.id
280 )
282```
283​
284***
285​
286### shapeOptions
287​
288```ts
289shapeOptions: ShapeStreamOptions<GetExtensions<T>>;
290```
291​
292Defined in: [packages/electric-db-collection/src/electric.ts:352](https://github.com/TanStack/db/blob/main/packages/electric-db-collection/src/electric.ts#L352)
293​
294Configuration options for the ElectricSQL ShapeStream
295​
296***
297​
298### syncMode?
299​
300```ts
301optional syncMode: ElectricSyncMode;
302```
303​
304Defined in: [packages/electric-db-collection/src/electric.ts:353](https://github.com/TanStack/db/blob/main/packages/electric-db-collection/src/electric.ts#L353)