callbag-state
Callbag-based state management.
npm i callbag-state
import state from 'callbag-state';
import subscribe from 'callbag-subscribe';
const s = state(42);
subscribe(v => console.log('GOT: ' + v))(s);
console.log(s.get());
s.set(43);
console.log(s.get());
► TRY IT!
Usage
👉 Track the state via .set()
and .get()
:
import state from 'callbag-state';
import subscribe from 'callbag-subscribe';
const s = state(42);
subscribe(console.log)(s);
s.set(43);
s.set(s.get() + 1);
► TRY IT!
👉 Track sub-states:
import state from 'callbag-state';
import subscribe from 'callbag-subscribe';
const s = state({x : 42});
const x = s.sub('x');
subscribe(console.log)(s);
subscribe(() => {})(x);
x.set(43);
x.set(x.get() + 1);
► TRY IT!
👉 Changes propagate properly wherever you make them on state-tree:
import state from 'callbag-state';
import subscribe from 'callbag-subscribe';
const s = state([{x : 42}, {x: 21}]);
subscribe(console.log)(s.sub(0).sub('x'));
s.set([{x: 44}]);
s.sub(0).set({x: 43});
s.sub(0).sub('x').set(45);
► TRY IT!
👉 Track changes:
import state from 'callbag-state';
import subscribe from 'callbag-subscribe';
const s = state([1, 2, 3, 4]);
subscribe(console.log)(s.downstream());
s.set([5, 2, 3, 4, 1]);
► TRY IT!
Gotchas
⚠️⚠️ A state (or one of its descendants) must be subscribed to in order for its value to be tracked properly:
const s = state(...)
const x = s.sub('x')
s.set(...)
x.get()
...
subscribe(() => {})(x);
s.set(...)
x.get()
⚠️⚠️ Don't change an object without changing its reference:
const s = state([1, 2, 3, 4])
s.get().push(5);
const s = state([1, 2, 3, 4])
s.set([...s.get(), 5]);
const s = state([1, 2, 3, 4])
s.sub(s.get().length).set(5)
► TRY IT!
Contribution
Be nice and respectful, more importantly super open and welcoming to all.
👉 Useful commands for working on this repo:
git clone https://github.com/loreanvictor/callbag-state.git
npm i
npm start
npm test
npm run cov:view