Open History to see the last commit
1---
2id: Transaction
3title: Transaction
4---
5
6# Interface: Transaction\<T\>
7
8Defined in: [packages/db/src/transactions.ts:208](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L208)
9
10## Type Parameters
11
12### T
13
14`T` *extends* `object` = `Record`\<`string`, `unknown`\>
15
16## Properties
17
18### autoCommit
19
20```ts
21autoCommit: boolean;
22```
23
24Defined in: [packages/db/src/transactions.ts:214](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L214)
25
26***
27
28### createdAt
29
30```ts
31createdAt: Date;
32```
33
34Defined in: [packages/db/src/transactions.ts:215](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L215)
35
36***
37
38### error?
39
40```ts
41optional error: object;
42```
43
44Defined in: [packages/db/src/transactions.ts:218](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L218)
45
46#### error
47
48```ts
49error: Error;
50```
51
52#### message
53
54```ts
55message: string;
56```
57
58***
59
60### id
61
62```ts
63id: string;
64```
65
66Defined in: [packages/db/src/transactions.ts:209](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L209)
67
68***
69
70### isPersisted
71
72```ts
73isPersisted: Deferred<Transaction<T>>;
74```
75
76Defined in: [packages/db/src/transactions.ts:213](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L213)
77
78***
79
80### metadata
81
82```ts
83metadata: Record<string, unknown>;
84```
85
86Defined in: [packages/db/src/transactions.ts:217](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L217)
87
88***
89
90### mutationFn
91
92```ts
93mutationFn: MutationFn<T>;
94```
95
96Defined in: [packages/db/src/transactions.ts:211](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L211)
97
98***
99
100### mutations
101
102```ts
103mutations: PendingMutation<T, OperationType, Collection<T, any, any, any, any>>[];
104```
105
106Defined in: [packages/db/src/transactions.ts:212](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L212)
107
108***
109
110### sequenceNumber
111
112```ts
113sequenceNumber: number;
114```
115
116Defined in: [packages/db/src/transactions.ts:216](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L216)
117
118***
119
120### state
121
122```ts
123state: TransactionState;
124```
125
126Defined in: [packages/db/src/transactions.ts:210](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L210)
127
128## Methods
129
130### applyMutations()
131
132```ts
133applyMutations(mutations): void;
134```
135
136Defined in: [packages/db/src/transactions.ts:327](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L327)
137
138Apply new mutations to this transaction, intelligently merging with existing mutations
139
140When mutations operate on the same item (same globalKey), they are merged according to
141the following rules:
142
143- **insert + update** → insert (merge changes, keep empty original)
144- **insert + delete** → removed (mutations cancel each other out)
145- **update + delete** → delete (delete dominates)
146- **update + update** → update (union changes, keep first original)
147- **same type** → replace with latest
148
149This merging reduces over-the-wire churn and keeps the optimistic local view
150aligned with user intent.
151
152#### Parameters
153
154##### mutations
155
156[`PendingMutation`](PendingMutation.md)\<`any`, [`OperationType`](../type-aliases/OperationType.md), [`Collection`](Collection.md)\<`any`, `any`, `any`, `any`, `any`\>\>[]
157
158Array of new mutations to apply
159
160#### Returns
161
162`void`
163
164***
165
166### commit()
167
168```ts
169commit(): Promise<Transaction<T>>;
170```
171
172Defined in: [packages/db/src/transactions.ts:472](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L472)
173
174Commit the transaction and execute the mutation function
175
176#### Returns
177
178`Promise`\<`Transaction`\<`T`\>\>
179
180Promise that resolves to this transaction when complete
181
182#### Examples
183
184```ts
185// Manual commit (when autoCommit is false)
186const tx = createTransaction({
187 autoCommit: false,
188 mutationFn: async ({ transaction }) => {
189 await api.saveChanges(transaction.mutations)
190 }
191})
192
193tx.mutate(() => {
194 collection.insert({ id: "1", text: "Buy milk" })
195})
196
197await tx.commit() // Manually commit
198```
199
200```ts
201// Handle commit errors
202try {
203 const tx = createTransaction({
204 mutationFn: async () => { throw new Error("API failed") }
205 })
206
207 tx.mutate(() => {
208 collection.insert({ id: "1", text: "Item" })
209 })
210
211 await tx.commit()
212} catch (error) {
213 console.log('Commit failed, transaction rolled back:', error)
214}
215```
216
217```ts
218// Check transaction state after commit
219await tx.commit()
220console.log(tx.state) // "completed" or "failed"
221```
222
223***
224
225### compareCreatedAt()
226
227```ts
228compareCreatedAt(other): number;
229```
230
231Defined in: [packages/db/src/transactions.ts:526](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L526)
232
233Compare two transactions by their createdAt time and sequence number in order
234to sort them in the order they were created.
235
236#### Parameters
237
238##### other
239
240`Transaction`\<`any`\>
241
242The other transaction to compare to
243
244#### Returns
245
246`number`
247
248-1 if this transaction was created before the other, 1 if it was created after, 0 if they were created at the same time
249
250***
251
252### mutate()
253
254```ts
255mutate(callback): Transaction<T>;
256```
257
258Defined in: [packages/db/src/transactions.ts:287](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L287)
259
260Execute collection operations within this transaction
261
262#### Parameters
263
264##### callback
265
266() => `void`
267
268Function containing collection operations to group together. If the
269callback returns a Promise, the transaction context will remain active until the promise
270settles, allowing optimistic writes after `await` boundaries.
271
272#### Returns
273
274`Transaction`\<`T`\>
275
276This transaction for chaining
277
278#### Examples
279
280```ts
281// Group multiple operations
282const tx = createTransaction({ mutationFn: async () => {
283 // Send to API
284}})
285
286tx.mutate(() => {
287 collection.insert({ id: "1", text: "Buy milk" })
288 collection.update("2", draft => { draft.completed = true })
289 collection.delete("3")
290})
291
292await tx.isPersisted.promise
293```
294
295```ts
296// Handle mutate errors
297try {
298 tx.mutate(() => {
299 collection.insert({ id: "invalid" }) // This might throw
300 })
301} catch (error) {
302 console.log('Mutation failed:', error)
303}
304```
305
306```ts
307// Manual commit control
308const tx = createTransaction({ autoCommit: false, mutationFn: async () => {} })
309
310tx.mutate(() => {
311 collection.insert({ id: "1", text: "Item" })
312})
313
314// Commit later when ready
315await tx.commit()
316```
317
318***
319
320### rollback()
321
322```ts
323rollback(config?): Transaction<T>;
324```
325
326Defined in: [packages/db/src/transactions.ts:389](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L389)
327
328Rollback the transaction and any conflicting transactions
329
330#### Parameters
331
332##### config?
333
334Configuration for rollback behavior
335
336###### isSecondaryRollback?
337
338`boolean`
339
340#### Returns
341
342`Transaction`\<`T`\>
343
344This transaction for chaining
345
346#### Examples
347
348```ts
349// Manual rollback
350const tx = createTransaction({ mutationFn: async () => {
351 // Send to API
352}})
353
354tx.mutate(() => {
355 collection.insert({ id: "1", text: "Buy milk" })
356})
357
358// Rollback if needed
359if (shouldCancel) {
360 tx.rollback()
361}
362```
363
364```ts
365// Handle rollback cascade (automatic)
366const tx1 = createTransaction({ mutationFn: async () => {} })
367const tx2 = createTransaction({ mutationFn: async () => {} })
368
369tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
370tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
371
372tx1.rollback() // This will also rollback tx2 due to conflict
373```
374
375```ts
376// Handle rollback in error scenarios
377try {
378 await tx.isPersisted.promise
379} catch (error) {
380 console.log('Transaction was rolled back:', error)
381 // Transaction automatically rolled back on mutation function failure
382}
383```
384
385***
386
387### setState()
388
389```ts
390setState(newState): void;
391```
392
393Defined in: [packages/db/src/transactions.ts:238](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L238)
394
395#### Parameters
396
397##### newState
398
399[`TransactionState`](../type-aliases/TransactionState.md)
400
401#### Returns
402
403`void`
404
405***
406
407### touchCollection()
408
409```ts
410touchCollection(): void;
411```
412
413Defined in: [packages/db/src/transactions.ts:417](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L417)
414
415#### Returns
416
417`void`