transaction
See source codeBatches 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
Name | Description |
---|---|
|
The function to run in a transaction, called with a function to roll back the change. |
Returns
T
Prev
transactNext
unsafe__withoutCapture