js-stateful

0.0.2 • Public • Published

Javascript State Management

State management for your vanilla JS apps 📫

Demo

View a demo here: https://samuelhornsey.github.io/js-stateful/demo/

Installation

Installing using npm

npm install js-stateful

import as module.

import Store from 'js-stateful'

Usage

Setting up and creating the store

import Store from 'js-stateful'

// Initial state
const state = {
  items: []
}

// Create an object containing mutations
const mutations = {
  ADD_ITEM: (state, action) => {
    state.items.push(action.item);

    return state;
  }
};

// Init the store
const store = new Store({ state, mutations, debug: true });

You can pass in a onChange handler. Everytime the state is changed this handler will be called.

store.onChange(state => {
  console.log(state);
});

To modify the state use an action. These will call a specific mutation. The dispatch function on the store will create and commit the action.

// Create an action function
const addItem = item => {
  return { type: "ADD_ITEM", item };
};

store.dispatch(addItem({ title: 'Hello, World' }));

To read the current state of the store simple use it like an other object.

console.log(store.state);

/js-stateful/

    Package Sidebar

    Install

    npm i js-stateful

    Weekly Downloads

    6

    Version

    0.0.2

    License

    MIT

    Unpacked Size

    11.3 kB

    Total Files

    10

    Last publish

    Collaborators

    • samhornsey