0.5.10 • Published 2 years ago

eldon-jstates v0.5.10

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

JStates

A super small, simple and fast ⚡ JavaScript state library

Also checkout JStates library for Reactjs

NPM

GitHub issues license npm bundle size npm

Why another state library

Many developers need a state to communicate between their services/components. I wanted to introduce a very small, simple state solution that would work for most cases.

In order to understand, compose or improve this library, you don't need more than to jump into the small source code and extend the functionality or create your own.

Note about modification

This is a fork of the original jstates project. I've added a "oldState" parameter to be passed to subscribed functions because it was a feature I needed. I submitted a pullrequest that is pending approval, until approval is given you can use this package to get the feature.

As soon as the pullrequest is accepted, please go use the original jstates library!

Install

npm i -S jstates

Usage

import { createState } from "jstates";
// types exported: import { JState, JStateSubscribers, JstateInstance } from "jstates";

const myState = createState({ counter: 0 });

function onUpdate(state) {
  console.log("onUpdate: counter changed to ", state.counter);
}

myState.subscribe(onUpdate);

// Updating with an object
myState.setState({ counter: ++myState.state.counter });
// => onUpdate: counter changed to  1

// Updating with a function
myState.setState((state) => ({ counter: ++state.counter }));
// => onUpdate: counter changed to  2

API

const initialState = {};
const stateInstance = createState(initialState);
/* => returns state Instance
{
  state,
  subscribers,
  setState,
  subscribe,
  unsubscribe,
};
*/

// Get the state
stateInstance.state;

// Change the state
stateInstance.setState(<object or a function that returns and object>);
// => returns a promise

// Subscribe to state changes
stateInstance.subscribe(<function that will be called with the state on each update>);


// Unsubscribe from state changes
stateInstance.unsubscribe(<function that already subscribed>);