createTransaction

Function: createTransaction()

ts
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

Type Parameters

T extends object = Record<string, unknown>

Parameters

config

TransactionConfig<T>

Transaction configuration with mutation function

Returns

Transaction<T>

A new Transaction instance

Examples

ts
// 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
ts
// 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)
}
ts
// 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()
Our Partners
Electric
Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.

Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.