globalAtom
globalAtom<T>(defaultValue: T, options: GlobalAtomOptions): GlobalAtom<T>valdres Creates a cross-store singleton atom
A global atom is a single shared value that stays in sync across every store
that touches it — writing in one store is immediately visible from any other.
This is the mechanism behind Valdres' @valdres/* browser-API packages: each
wraps one global atom around a browser subscription, so any store in the app
sees the same online status, geolocation position, and so on.
options.name is required — it is the atom's global address. Re-using a name
that's already registered throws.
Usage
import { globalAtom } from "valdres"
const onlineAtom = globalAtom(navigator.onLine, { name: "app/online" })
Same call shape as atom — the only difference is that
options.name is required instead of optional.
The self-accessors
A global atom carries three extra methods beyond the ordinary atom surface,
for reading and writing it without a Store handle:
onlineAtom.getSelf() // read the current value
onlineAtom.setSelf(false) // write — fans out to every store
onlineAtom.resetSelf() // restore the default value everywhere
These are what a browser-API package's onMount uses to push external events
(a navigator.onLine change, a geolocation update, …) into the shared value:
const onlineAtom = globalAtom(navigator.onLine, {
name: "app/online",
onMount: () => {
const update = () => onlineAtom.setSelf(navigator.onLine)
window.addEventListener("online", update)
window.addEventListener("offline", update)
return () => {
window.removeEventListener("online", update)
window.removeEventListener("offline", update)
}
},
})
onMount fires once, when the FIRST subscriber across ANY store attaches, and
its cleanup fires once, when the LAST subscriber across ALL stores detaches —
so the underlying browser subscription is shared, not duplicated per store.
Parameters
globalAtom accepts the same options as atom (schema,
schemaValidation, onSet, onMount, maxAge, mutable,
staleWhileRevalidate, staleIfError) as GlobalAtomOptions — identical to
AtomOptions, except name is required instead of optional.
See also
- atom — create a single, per-store atom
- globalAtomFamily — a keyed collection of global atoms