useTransaction

Signature
useTransaction(store?: Store): (callback: (txn: Transaction) => any) => any

valdres-react Batch updates — subscribers fire once

Returns a function that runs a callback as a transaction on the current store: all updates apply atomically and subscribers fire once at the end. The callback receives { set, get, reset, del, unset }.

Usage

import { atom } from "valdres"
import { useTransaction } from "valdres-react"

const firstNameAtom = atom("")
const lastNameAtom = atom("")

function ResetForm() {
    const txn = useTransaction()
    const clear = () =>
        txn(({ reset }) => {
            reset(firstNameAtom)
            reset(lastNameAtom)
        })
    return <button onClick={clear}>Clear</button>
}

Pass a store to target one explicitly: useTransaction(myStore).

See also