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

Transaction.md

494 lines10.6 KB

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