AtomJS
AtomJS is a simple way to manage the app state. Stolen from Clojure (like everything else in JS world). You can find all information about atoms here.
npm i -S atomjs
API
atom(initialState) -> atomSymbol
Returns atomSymbol
, which is reference to atom's state.
deref(atomSymbol) -> atomState
Returns current state of atom.
reset(atomSymbol, value) -> value
Changes atom's state to value
and returns it.
swap(atomSymbol, fn[, ...args]) -> fn(atomState, ...args)
Changes atom's state to fn(atomState, ...args)
and returns it.
addWatch(atomSymbol, cb) -> removeWatch
Sets cb
as a listener for atom. cb
will be called every time atom's state mutates (through reset
or swap
). Returns removeWatch
function.
removeWatch()
Removes listener.
Example
const {atom, deref, swap, reset, addWatch} = require('atomjs');
const intAtom = atom(1);
deref(intAtom); // 1
const intAtomWatcher = addWatch(intAtom, (state) => {
console.log(state);
});
reset(intAtom, 3);
// log: 3
function sum(a, b) {
return a + b;
}
swap(intAtom, sum, 4);
// log: 7
intAtomWatcher(); // Remove watcher
reset(intAtom, 5);
// Nothing will be logged here as watcher was removed.
deref(intAtom); // 5