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