Search documentation

Search all pages, headings and text, in the current package or topic or in all documentation.

Batches and transactions

Group notifications with batch, or make several writes all-or-nothing with transaction.

@workspace/active-state 1.0.1Developmentunreleased, in development in Foundationbaseline ce081dc3

An all-or-nothing transferClient

Savings
100
Current
20
Total
120

batch: one notification for several writes#

TypeScript
import {batch} from '@workspace/active-state';
batch(() => {  first.setState('Ada');  last.setState('Lovelace');}); // subscribers run once, after both writes

Writes inside a batch are readable at once and published together when the outermost batch ends. A batch never reverts anything: if the callback throws, its writes stay, are published, and the error is rethrown.

transaction: all or nothing#

TypeScript
import {transaction} from '@workspace/active-state';
transaction(() => {  current.update((value) => value + amount);  savings.update((value) => value - amount);  if (savings.state < 0) throw new Error('Not enough savings');});
  • Reads inside see the transaction's own writes, for stores and derived values alike.
  • When the callback throws, every store and derived value it touched is restored, nothing is published, and the first error is rethrown to you.
  • A nested transaction joins the open one; there are no savepoints.
  • Only local state is reverted: a request, a DOM change or a copy in another variable is not.
  • Structural calls (subscribing, disposing, creating effects or operations) are refused inside a transaction; invoke() waits until it commits.

Both are synchronous: a callback that returns a promise is refused with a TypeError.

This page as Markdown