function createTransaction<T>(config): Transaction<T>
function createTransaction<T>(config): Transaction<T>
Defined in: packages/db/src/transactions.ts:74
Creates a new transaction for grouping multiple collection operations
• T extends object = Record<string, unknown>
Transaction configuration with mutation function
Transaction<T>
A new Transaction instance
// Basic transaction usage
const tx = createTransaction({
mutationFn: async ({ transaction }) => {
// Send all mutations to API
await api.saveChanges(transaction.mutations)
}
})
tx.mutate(() => {
collection.insert({ id: "1", text: "Buy milk" })
collection.update("2", draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Basic transaction usage
const tx = createTransaction({
mutationFn: async ({ transaction }) => {
// Send all mutations to API
await api.saveChanges(transaction.mutations)
}
})
tx.mutate(() => {
collection.insert({ id: "1", text: "Buy milk" })
collection.update("2", draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Handle transaction errors
try {
const tx = createTransaction({
mutationFn: async () => { throw new Error("API failed") }
})
tx.mutate(() => {
collection.insert({ id: "1", text: "New item" })
})
await tx.isPersisted.promise
} catch (error) {
console.log('Transaction failed:', error)
}
// Handle transaction errors
try {
const tx = createTransaction({
mutationFn: async () => { throw new Error("API failed") }
})
tx.mutate(() => {
collection.insert({ id: "1", text: "New item" })
})
await tx.isPersisted.promise
} catch (error) {
console.log('Transaction failed:', error)
}
// Manual commit control
const tx = createTransaction({
autoCommit: false,
mutationFn: async () => {
// API call
}
})
tx.mutate(() => {
collection.insert({ id: "1", text: "Item" })
})
// Commit later
await tx.commit()
// Manual commit control
const tx = createTransaction({
autoCommit: false,
mutationFn: async () => {
// API call
}
})
tx.mutate(() => {
collection.insert({ id: "1", text: "Item" })
})
// Commit later
await tx.commit()
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.