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

executeTransaction.md

83 lines1.8 KB

1---
2id: executeTransaction
3title: executeTransaction
4---
5​
6```ts
7function executeTransaction<T>(
8 db,
9 storeNames,
10 mode,
11callback): Promise<T>;
12```
13​
14Defined in: packages/db/src/indexed-db-wrapper.ts:248
15​
16Executes a callback within an IndexedDB transaction.
17​
18This function handles transaction lifecycle automatically:
19- Creates the transaction with the specified mode
20- Provides the transaction and object stores to the callback
21- Waits for both the callback and the transaction to complete (or abort)
22- Returns the callback's result or rejects with an error
23​
24IndexedDB can commit while an async callback is still pending. If that callback
25later rejects, this function rejects but cannot undo the committed writes.
26​
27## Type Parameters
28​
29### T
30​
31`T`
32​
33The return type of the callback
34​
35## Parameters
36​
37### db
38​
39`IDBDatabase`
40​
41The IDBDatabase instance
42​
43### storeNames
44​
45A single store name or array of store names to include in the transaction
46​
47`string` | `string`[]
48​
49### mode
50​
51`IDBTransactionMode`
52​
53The transaction mode ('readonly', 'readwrite', or 'readwriteflush')
54​
55### callback
56​
57(`transaction`, `stores`) => `T` \| `Promise`\<`T`\>
58​
59A function that performs operations within the transaction.
60 Receives the transaction and a record of object stores keyed by name.
61 Can be sync or async.
62​
63## Returns
64​
65`Promise`\<`T`\>
66​
67A promise that resolves to the callback's return value when the transaction completes
68​
69## Example
70​
71```typescript
72// Single store
73const result = await executeTransaction(db, 'todos', 'readwrite', (tx, stores) => {
74 stores.todos.put({ id: 1, text: 'Buy milk' })
75 return 'done'
76})
77​
78// Multiple stores
79await executeTransaction(db, ['todos', 'users'], 'readwrite', (tx, stores) => {
80 stores.todos.put({ id: 1, text: 'Task' })
81 stores.users.put({ id: 1, name: 'Alice' })
82})
83```