orYoffe / jstates

JStates - A simple js state library

Home Page:https://medium.com/@Or_yoffe/a-simple-small-javascript-state-library-called-jstates-%EF%B8%8F-c4c366a6ea1a

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SWUbanner






jstates Logo







JStates

A super small, simple and fast ⚡ JavaScript state library A simple Observer (publisher - subscriber) pattern implementaion

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.

Install

npm i -S jstates

Usage

Counter

import { createState } from "jstates";
// types exported: import { JStateGetState, SubFunction, 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

Todos (TS)

import { createState } from "jstates";
const todosState = createState<TodoState>({
  todos: [],
});

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

todosState.subscribe(onUpdate);

function removeTodo(todo: string) {
  todosState.setState((s: typeof todosState.state) => ({
    todos: s.todos.filter((t: string) => t !== todo),
  }));
}

const addTodo = (todo: string) => {
  todosState.setState((s: typeof todosState.state) => ({
    todos: s.todos.concat(todo),
  }));
};

addTodo("Buy milk");
addTodo("Buy eggs");

About

JStates - A simple js state library

https://medium.com/@Or_yoffe/a-simple-small-javascript-state-library-called-jstates-%EF%B8%8F-c4c366a6ea1a

License:MIT License


Languages

Language:TypeScript 100.0%