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