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