transaction

See source code

Batches state updates, deferring side effects until after the transaction completes.

function transaction<T>(fn: (rollback: () => void) => T): T

Example

const firstName = atom('John')
const lastName = atom('Doe')

react('greet', () => {
  print(`Hello, ${firstName.get()} ${lastName.get()}!`)
})

// Logs "Hello, John Doe!"

transaction(() => {
  firstName.set('Jane')
  lastName.set('Smith')
})

// Logs "Hello, Jane Smith!"

If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began.

const firstName = atom('John')
const lastName = atom('Doe')

react('greet', () => {
  print(`Hello, ${firstName.get()} ${lastName.get()}!`)
})

// Logs "Hello, John Doe!"

transaction(() => {
  firstName.set('Jane')
  throw new Error('oops')
})

// Does not log
// firstName.get() === 'John'

A rollback callback is passed into the function. Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.

const firstName = atom('John')
const lastName = atom('Doe')

react('greet', () => {
  print(`Hello, ${firstName.get()} ${lastName.get()}!`)
})

// Logs "Hello, John Doe!"

transaction((rollback) => {
  firstName.set('Jane')
  lastName.set('Smith')
  rollback()
})

// Does not log
// firstName.get() === 'John'
// lastName.get() === 'Doe'

Parameters

NameDescription

fn

(rollback: () => void) => T

The function to run in a transaction, called with a function to roll back the change.

Returns

T
Prev
transact
Next
unsafe__withoutCapture

We use cookies on this website.
Learn more in our Cookie Policy.