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

Transaction.md

425 lines8.4 KB

1---
2id: Transaction
3title: Transaction
4---
5​
6# Interface: Transaction\<T\>
7​
8Defined in: [packages/db/src/transactions.ts:209](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L209)
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:215](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L215)
25​
26***
27​
28### createdAt
29​
30```ts
31createdAt: Date;
32```
33​
34Defined in: [packages/db/src/transactions.ts:216](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L216)
35​
36***
37​
38### error?
39​
40```ts
41optional error: object;
42```
43​
44Defined in: [packages/db/src/transactions.ts:219](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L219)
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:210](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L210)
67​
68***
69​
70### isPersisted
71​
72```ts
73isPersisted: Deferred<Transaction<T>>;
74```
75​
76Defined in: [packages/db/src/transactions.ts:214](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L214)
77​
78***
79​
80### metadata
81​
82```ts
83metadata: Record<string, unknown>;
84```
85​
86Defined in: [packages/db/src/transactions.ts:218](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L218)
87​
88***
89​
90### mutationFn
91​
92```ts
93mutationFn: MutationFn<T>;
94```
95​
96Defined in: [packages/db/src/transactions.ts:212](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L212)
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:213](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L213)
107​
108***
109​
110### sequenceNumber
111​
112```ts
113sequenceNumber: number;
114```
115​
116Defined in: [packages/db/src/transactions.ts:217](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L217)
117​
118***
119​
120### state
121​
122```ts
123state: TransactionState;
124```
125​
126Defined in: [packages/db/src/transactions.ts:211](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L211)
127​
128## Methods
129​
130### applyMutations()
131​
132```ts
133applyMutations(mutations): void;
134```
135​
136Defined in: [packages/db/src/transactions.ts:336](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L336)
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:493](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L493)
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)
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:547](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L547)
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:296](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L296)
259​
260Execute collection operations within this transaction
261​
262#### Parameters
263​
264##### callback
265​
266() => `void`
267​
268Synchronous function containing collection operations to group together.
269The transaction context is active only for the synchronous duration of this callback.
270Async work should happen in `mutationFn`; collection operations after `await` boundaries
271inside this callback will not be part of this transaction. For manual transactions, call
272`mutate` multiple times before committing to add more synchronous operations to the same
273transaction.
274​
275#### Returns
276​
277`Transaction`\<`T`\>
278​
279This transaction for chaining
280​
281#### Examples
282​
283```ts
284// Group multiple operations
285const tx = createTransaction({ mutationFn: async () => {
286 // Send to API
287}})
288​
289tx.mutate(() => {
290 collection.insert({ id: "1", text: "Buy milk" })
291 collection.update("2", draft => { draft.completed = true })
292 collection.delete("3")
293})
294​
295await tx.isPersisted.promise
296```
297​
298```ts
299// Handle mutate errors
300try {
301 tx.mutate(() => {
302 collection.insert({ id: "invalid" }) // This might throw
303 })
304} catch (error) {
305 console.log('Mutation failed:', error)
307```
308​
309```ts
310// Manual commit control
311const tx = createTransaction({ autoCommit: false, mutationFn: async () => {} })
312​
313tx.mutate(() => {
314 collection.insert({ id: "1", text: "Item" })
315})
316​
317// Add more synchronous mutations to the same transaction
318tx.mutate(() => {
319 collection.update("1", draft => { draft.text = "Updated item" })
320})
321​
322// Commit later when ready
323await tx.commit()
324```
325​
326***
327​
328### rollback()
329​
330```ts
331rollback(config?): Transaction<T>;
332```
333​
334Defined in: [packages/db/src/transactions.ts:410](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L410)
335​
336Rollback the transaction and any conflicting transactions
337​
338#### Parameters
339​
340##### config?
341​
342Configuration for rollback behavior
343​
344###### isSecondaryRollback?
345​
346`boolean`
347​
348#### Returns
349​
350`Transaction`\<`T`\>
351​
352This transaction for chaining
353​
354#### Examples
355​
356```ts
357// Manual rollback
358const tx = createTransaction({ mutationFn: async () => {
359 // Send to API
360}})
361​
362tx.mutate(() => {
363 collection.insert({ id: "1", text: "Buy milk" })
364})
365​
366// Rollback if needed
367if (shouldCancel) {
368 tx.rollback()
370```
371​
372```ts
373// Handle rollback cascade (automatic)
374const tx1 = createTransaction({ mutationFn: async () => {} })
375const tx2 = createTransaction({ mutationFn: async () => {} })
376​
377tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
378tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
379​
380tx1.rollback() // This will also rollback tx2 due to conflict
381```
382​
383```ts
384// Handle rollback in error scenarios
385try {
386 await tx.isPersisted.promise
387} catch (error) {
388 console.log('Transaction was rolled back:', error)
389 // Transaction automatically rolled back on mutation function failure
391```
392​
393***
394​
395### setState()
396​
397```ts
398setState(newState): void;
399```
400​
401Defined in: [packages/db/src/transactions.ts:239](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L239)
402​
403#### Parameters
404​
405##### newState
406​
407[`TransactionState`](../type-aliases/TransactionState.md)
408​
409#### Returns
410​
411`void`
412​
413***
414​
415### touchCollection()
416​
417```ts
418touchCollection(): void;
419```
420​
421Defined in: [packages/db/src/transactions.ts:438](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L438)
422​
423#### Returns
424​
425`void`