@rogalski/state-manager

This module allows distributed state management including before and after state change actions.

Usage no npm install needed!

<script type="module">
  import rogalskiStateManager from 'https://cdn.skypack.dev/@rogalski/state-manager';
</script>

README

State Manager

This module allows distributed state management including before and after state change actions.

Instalation

npm i @rogalski/state-manager

Usage

import createStateManager from "@rogalski/state-manager"

/** first create state manager by adding multiple states */
const stateManager = createStateManager({
    stateA: {
        a: "a",
        b: "b",
        c: {
            d: 1,
            e: true
        }
    },
    stateB: {
        //...
    }
    //...
})

/** then get state controller */
const controllerA = stateManager.getController("stateA")


/** get state, set state, add actions before and after state change */
// returns copy of stateA
controllerA.getState()

// sets value of param a of stateA to 'c'
controllerA.setState({ a: "c" })

 // logs a message allways before stateA will be updated
controllerA.willUpdateState((newState, oldState) => { console.log("Updating stateA"})

 // logs a message allways after updating stateA
controllerA.didUpdateState((newState, oldState) => { console.log("stateA succesfully updated"})

/** delete controller and all its actions */
// this will destroy controller - actions defined by controller.willUpdateState() and controller.didUpdateState() will be removed from the registry. This is usefull f.e. when working with React - this function shold be called when a component that uses controller gets unmounted.
controllerA.destroy()