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

Transaction.md

491 lines10.1 KB

1---
2id: Transaction
3title: Transaction
4---
5​
6Defined in: [packages/db/src/transactions.ts:350](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L350)
7​
8## Type Parameters
9​
10### T
11​
12`T` *extends* `object` = `Record`\<`string`, `unknown`\>
13​
14## Properties
15​
16### autoCommit
17​
18```ts
19autoCommit: boolean;
20```
21​
22Defined in: [packages/db/src/transactions.ts:362](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L362)
23​
24***
25​
26### collections
27​
28```ts
29readonly collections: Set<Collection<any, any, any, any, any>>;
30```
31​
32Defined in: [packages/db/src/transactions.ts:359](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L359)
33​
34Every Collection that has tracked this transaction. Settlement recomputes
35each of them, including one whose mutations merged away.
36​
37***
38​
39### createdAt
40​
41```ts
42createdAt: Date;
43```
44​
45Defined in: [packages/db/src/transactions.ts:363](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L363)
46​
47***
48​
49### error?
50​
51```ts
52optional error: object;
53```
54​
55Defined in: [packages/db/src/transactions.ts:366](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L366)
56​
57#### error
58​
59```ts
60error: Error;
61```
62​
63#### message
64​
65```ts
66message: string;
67```
68​
69***
70​
71### id
72​
73```ts
74id: string;
75```
76​
77Defined in: [packages/db/src/transactions.ts:351](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L351)
78​
79***
80​
81### metadata
82​
83```ts
84metadata: Record<string, unknown>;
85```
86​
87Defined in: [packages/db/src/transactions.ts:365](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L365)
88​
89***
90​
91### mutationFn
92​
93```ts
94mutationFn: MutationFn<T>;
95```
96​
97Defined in: [packages/db/src/transactions.ts:353](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L353)
98​
99***
100​
101### mutations
102​
103```ts
104mutations: PendingMutation<T, OperationType, Collection<T, any, any, any, any>>[];
105```
106​
107Defined in: [packages/db/src/transactions.ts:354](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L354)
108​
109***
110​
111### sequenceNumber
112​
113```ts
114sequenceNumber: number;
115```
116​
117Defined in: [packages/db/src/transactions.ts:364](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L364)
118​
119***
120​
121### state
122​
123```ts
124state: TransactionState;
125```
126​
127Defined in: [packages/db/src/transactions.ts:352](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L352)
128​
129## Methods
130​
131### applyMutations()
132​
133```ts
134applyMutations(mutations): void;
135```
136​
137Defined in: [packages/db/src/transactions.ts:566](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L566)
138​
139Apply new mutations to this transaction, intelligently merging with existing mutations
140​
141When mutations operate on the same item (same globalKey), they are merged according to
142the following rules:
143​
144- **insert + update** → insert (merge changes, keep empty original)
145- **insert + delete** → removed (mutations cancel each other out)
146- **update + delete** → delete (delete dominates)
147- **update + update** → update (union changes, keep first original)
148- **delete + insert** → removed if restored, otherwise update
149- **same type** → replace with latest
150​
151This merging reduces over-the-wire churn and keeps the optimistic local view
152aligned with user intent.
153​
154#### Parameters
155​
156##### mutations
157​
158[`PendingMutation`](PendingMutation.md)\<`any`, [`OperationType`](../type-aliases/OperationType.md), [`Collection`](Collection.md)\<`any`, `any`, `any`, `any`, `any`\>\>[]
159​
160Array of new mutations to apply
161​
162#### Returns
163​
164`void`
165​
166***
167​
168### commit()
169​
170```ts
171commit(): Promise<Transaction<T>>;
172```
173​
174Defined in: [packages/db/src/transactions.ts:745](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L745)
175​
176Commit the transaction and execute the mutation function
177​
178#### Returns
179​
180`Promise`\<`Transaction`\<`T`\>\>
181​
182Promise that resolves to this transaction when complete
183​
184#### Examples
185​
186```ts
187// Manual commit (when autoCommit is false)
188const tx = createTransaction({
189 autoCommit: false,
190 mutationFn: async ({ transaction }) => {
191 await api.saveChanges(transaction.mutations)
192 }
193})
194​
195tx.mutate(() => {
196 collection.insert({ id: "1", text: "Buy milk" })
197})
198​
199await tx.commit() // Manually commit
200```
201​
202```ts
203// Handle commit errors
204try {
205 const tx = createTransaction({
206 mutationFn: async () => { throw new Error("API failed") }
207 })
208​
209 tx.mutate(() => {
210 collection.insert({ id: "1", text: "Item" })
211 })
212​
213 await tx.commit()
214} catch (error) {
215 console.log('Commit failed, transaction rolled back:', error)
217```
218​
219```ts
220// Check transaction state after commit
221await tx.commit()
222console.log(tx.state) // "completed" or "failed"
223```
224​
225***
226​
227### compareCreatedAt()
228​
229```ts
230compareCreatedAt(other): number;
231```
232​
233Defined in: [packages/db/src/transactions.ts:817](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L817)
234​
235Compare two transactions by their createdAt time and sequence number in order
236to sort them in the order they were created.
237​
238#### Parameters
239​
240##### other
241​
242`Transaction`\<`any`\>
243​
244The other transaction to compare to
245​
246#### Returns
247​
248`number`
249​
250-1 if this transaction was created before the other, 1 if it was created after, 0 if they were created at the same time
251​
252***
253​
254### completeWithoutCommit()
255​
256```ts
257completeWithoutCommit(): void;
258```
259​
260Defined in: [packages/db/src/transactions.ts:411](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L411)
261​
262**`Internal`**
263​
264Complete a transaction whose work was already applied outside commit().
265​
266#### Returns
267​
268`void`
269​
270***
271​
272### mutate()
273​
274```ts
275mutate(callback): Transaction<T>;
276```
277​
278Defined in: [packages/db/src/transactions.ts:475](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L475)
279​
280Execute collection operations within this transaction
281​
282#### Parameters
283​
284##### callback
285​
286() => `void`
287​
288Synchronous function containing collection operations to group together.
289The transaction context is active only for the synchronous duration of this callback.
290Async work should happen in `mutationFn`; collection operations after `await` boundaries
291inside this callback will not be part of this transaction. For manual transactions, call
292`mutate` multiple times before committing to add more synchronous operations to the same
293transaction. If this callback throws, its mutations are removed before the
294error reaches the caller; mutations from earlier successful calls remain.
295​
296#### Returns
297​
298`Transaction`\<`T`\>
299​
300This transaction for chaining
301​
302#### Examples
303​
304```ts
305// Group multiple operations
306const tx = createTransaction({ mutationFn: async () => {
307 // Send to API
308}})
309​
310tx.mutate(() => {
311 collection.insert({ id: "1", text: "Buy milk" })
312 collection.update("2", draft => { draft.completed = true })
313 collection.delete("3")
314})
315​
316await tx.when('settled')
317```
318​
319```ts
320// Handle mutate errors
321try {
322 tx.mutate(() => {
323 collection.insert({ id: "invalid" }) // This might throw
324 })
325} catch (error) {
326 console.log('Mutation failed:', error)
328```
329​
330```ts
331// Manual commit control
332const tx = createTransaction({ autoCommit: false, mutationFn: async () => {} })
333​
334tx.mutate(() => {
335 collection.insert({ id: "1", text: "Item" })
336})
337​
338// Add more synchronous mutations to the same transaction
339tx.mutate(() => {
340 collection.update("1", draft => { draft.text = "Updated item" })
341})
342​
343// Commit later when ready
344await tx.commit()
345```
346​
347***
348​
349### rollback()
350​
351```ts
352rollback(config?): Transaction<T>;
353```
354​
355Defined in: [packages/db/src/transactions.ts:638](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L638)
356​
357Rollback the transaction and any conflicting transactions
358​
359#### Parameters
360​
361##### config?
362​
363Configuration for rollback behavior
364​
365###### error?
366​
367`Error`
368​
369###### isSecondaryRollback?
370​
371`boolean`
372​
373#### Returns
374​
375`Transaction`\<`T`\>
376​
377This transaction for chaining
378​
379#### Examples
380​
381```ts
382// Manual rollback
383const tx = createTransaction({ mutationFn: async () => {
384 // Send to API
385}})
386​
387tx.mutate(() => {
388 collection.insert({ id: "1", text: "Buy milk" })
389})
390​
391// Rollback if needed
392if (shouldCancel) {
393 tx.rollback()
395```
396​
397```ts
398// Handle rollback cascade (automatic)
399const tx1 = createTransaction({ mutationFn: async () => {} })
400const tx2 = createTransaction({ mutationFn: async () => {} })
401​
402tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
403tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
404​
405tx1.rollback() // This will also rollback tx2 due to conflict
406```
407​
408```ts
409// Handle rollback in error scenarios
410try {
411 await tx.when('settled')
412} catch (error) {
413 console.log('Transaction was rolled back:', error)
414 // Transaction automatically rolled back on mutation function failure
416```
417​
418***
419​
420### setState()
421​
422```ts
423setState(newState): void;
424```
425​
426Defined in: [packages/db/src/transactions.ts:417](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L417)
427​
428#### Parameters
429​
430##### newState
431​
432[`TransactionState`](../type-aliases/TransactionState.md)
433​
434#### Returns
435​
436`void`
437​
438***
439​
440### touchCollection()
441​
442```ts
443touchCollection(releasedHold): void;
444```
445​
446Defined in: [packages/db/src/transactions.ts:684](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L684)
447​
448Tell every Collection that tracked this transaction that it changed. A
449failure in one Collection must not leave the others showing this
450transaction's settled optimistic state, so each one recomputes before the
451first error is thrown. A settled transaction then empties its set of
452tracking Collections. Its mutations still name their Collection.
453​
454#### Parameters
455​
456##### releasedHold
457​
458`boolean` = `false`
459​
460#### Returns
461​
462`void`
463​
464***
465​
466### when()
467​
468```ts
469when(_state): Promise<Transaction<T>>;
470```
471​
472Defined in: [packages/db/src/transactions.ts:406](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L406)
473​
474Wait for this transaction to complete successfully or fail.
475​
476The promise resolves with this transaction on success and rejects with
477the original error on failure (or `undefined` for a rollback without an
478error). For non-empty commits, this
479boundary is the mutation function's completion; it does not inherently
480prove backend acknowledgement or read-back unless the mutation function
481or an adapter-registered commit work item waits for it.
482​
483#### Parameters
484​
485##### \_state
486​
487`"settled"`
488​
489#### Returns
490​
491`Promise`\<`Transaction`\<`T`\>\>