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

Transaction.md

436 lines8.9 KB

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