A state object that is conditionally watchable on first depth only.
npm i -s @malipetek/straigtforward-state
or
yarn add @malipetek/straigtforward-state
import state from "@malipetek/straigtforward-state";
or
const state = require("@malipetek/straigtforward-state");
Alternatively you can get instances like this:
import { newState } from "@malipetek/straigtforward-state";
const state1 = newState();
const state2 = newState();
state.set = { things: [1,2,3], numberOfThings: 6, aLotOfThings: false };
or
state.set({ things: [1,2,3], numberOfThings: 3, aLotOfThings: false });
Access values as usual
state.things // [1,2,3]
state.numberOfThings // 3
Set the state properties as usual. When set watchers will be run, mutations does not trigger however, like pushing to an array value.
state.things = [...state.things, 4];
state.watch.things = (val, was) => {
val // [1,2,3,4]
state.things // [1,2,3,4]
state.numberOfThings = state.things.length;
};
state.watch.numberOfThings((val, was) => {
val // 4
was // 3
});
state.watch.all = (changedKey, val, was) => {
changedKey // 'things', 'numberOfThings'
state[changedKey] // [1], 1
val // [1], 1
was // [1,2,3], 3
};
state.things = [1];
state.numberOfThings = 1;
state.when.things.watch.numberOfThings(callback);
// or
const newThings = [1,2];
state.when.things.is(newThings).watch.numberOfThings = (val, was) => {
val // === newThings
};
state.things = newThings;
state.when.numberOfThings.or.aLotOfThings.watch.things((val, was) => {
});
state.when.numberOfThings.and.aLotOfThings.watch.things = (val, was) => {
// fires once
};
state.things = [1,2,3,4];
state.aLotOfThings = true;
state.things = [1,2,3,4];
Is operator can take a value or a function with 1 param that is the state member.
state.when.numberOfThings.is(v => v.length > 6).and.aLotOfThings.is(false).watch.things((things) => {
state.aLotOfThings = true;
});
state.things = [1,2,3,4,5,6,7,8];
more and less operators only can be used after is fn call followed by a or.
state.when.numberOfThings.is(6).or.more.watch.things(callback);