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

createTransaction.md

87 lines1.6 KB

1---
2id: createTransaction
3title: createTransaction
4---
5​
6# Function: createTransaction()
7​
8```ts
9function createTransaction<T>(config): Transaction<T>;
10```
11​
12Defined in: [packages/db/src/transactions.ts:156](https://github.com/TanStack/db/blob/main/packages/db/src/transactions.ts#L156)
13​
14Creates a new transaction for grouping multiple collection operations
15​
16## Type Parameters
17​
18### T
19​
20`T` *extends* `object` = `Record`\<`string`, `unknown`\>
21​
22## Parameters
23​
24### config
25​
26[`TransactionConfig`](../interfaces/TransactionConfig.md)\<`T`\>
27​
28Transaction configuration with mutation function
29​
30## Returns
31​
32[`Transaction`](../interfaces/Transaction.md)\<`T`\>
33​
34A new Transaction instance
35​
36## Examples
37​
38```ts
39// Basic transaction usage
40const tx = createTransaction({
41 mutationFn: async ({ transaction }) => {
42 // Send all mutations to API
43 await api.saveChanges(transaction.mutations)
44 }
45})
46​
47tx.mutate(() => {
48 collection.insert({ id: "1", text: "Buy milk" })
49 collection.update("2", draft => { draft.completed = true })
50})
51​
52await tx.isPersisted.promise
53```
54​
55```ts
56// Handle transaction errors
57try {
58 const tx = createTransaction({
59 mutationFn: async () => { throw new Error("API failed") }
60 })
61​
62 tx.mutate(() => {
63 collection.insert({ id: "1", text: "New item" })
64 })
65​
66 await tx.isPersisted.promise
67} catch (error) {
68 console.log('Transaction failed:', error)
70```
71​
72```ts
73// Manual commit control
74const tx = createTransaction({
75 autoCommit: false,
76 mutationFn: async () => {
77 // API call
78 }
79})
80​
81tx.mutate(() => {
82 collection.insert({ id: "1", text: "Item" })
83})
84​
85// Commit later
86await tx.commit()
87```