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