transaction

See source code

Batches state updates, deferring side effects until after the transaction completes. Unlike transact, this function always creates a new transaction, allowing for nested transactions.

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

Example

const firstName = atom("firstName", "John");
const lastName = atom("lastName", "Doe");

react("greet", () => {
  console.log(`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. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.

const firstName = atom("firstName", "John");
const lastName = atom("lastName", "Doe");

react("greet", () => {
  console.log(`Hello, ${firstName.get()} ${lastName.get()}!`);
});

// Logs "Hello, John Doe!"

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

// firstName.get() === 'John'
// Logs "Hello, John Doe!" again: effects whose parents were changed and restored still run,
// and observe the restored values.

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("firstName", "John");
const lastName = atom("lastName", "Doe");

react("greet", () => {
  console.log(`Hello, ${firstName.get()} ${lastName.get()}!`);
});

// Logs "Hello, John Doe!"

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

// firstName.get() === 'John'
// lastName.get() === 'Doe'
// Logs "Hello, John Doe!" again, as above.

Parameters

NameDescription

fn

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

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

Returns

T;

The return value of the function

Prev
transact
Next
unsafe__withoutCapture