Skip to main content

transaction()

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

Example

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

react('greet', () => {
console.log(`Hello, ${firstName.value} ${lastName.value}!`)
})

// 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.

Example

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

react('greet', () => {
console.log(`Hello, ${firstName.value} ${lastName.value}!`)
})

// Logs "Hello, John Doe!"

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

// Does not log
// firstName.value === '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.

Example

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

react('greet', () => {
console.log(`Hello, ${firstName.value} ${lastName.value}!`)
})

// Logs "Hello, John Doe!"

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

// Does not log
// firstName.value === 'John'
// lastName.value === 'Doe'

Signature

transaction<T>(fn: Function): T;

Type parameters

  • T

Parameters

NameTypeDescription
fn(rollback: () => void) => TThe function to run in a transaction, called with a function to roll back the change.

Returns

T

Defined in: signia/src/transactions.ts:209