Skip to content

Latest commit

 

History

History
159 lines (115 loc) · 4.2 KB

README.md

File metadata and controls

159 lines (115 loc) · 4.2 KB

Straightforward State

Percentage of issues still open Average time to resolve an issue

GitHub stars

Npm package total downloads Npm package total downloads

Npm package total downloads

Npm package total downloads

A state object that is conditionally watchable on first depth only.

Play

On codesandbox:

Edit magical-wilbur-f247um

On Stackblitz:

Edit on Stackblitz

Install:

npm i -s @malipetek/straigtforward-state

or

yarn add @malipetek/straigtforward-state

import or require

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();

Initialize

state.set = { things: [1,2,3], numberOfThings: 6, aLotOfThings: false };

or

state.set({ things: [1,2,3], numberOfThings: 3, aLotOfThings: false });

Access

Access values as usual

state.things // [1,2,3]
state.numberOfThings // 3

Set

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];

Watch

Watch a member

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
});

Watch All

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;

Conditional watch

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;

and, or Operators

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

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

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);

👉 Submit feedback

👉 Submit issues