1.0.0 • Published 12 months ago

jstates v1.0.0

Weekly downloads
84
License
MIT
Repository
github
Last release
12 months ago

SWUbanner

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

12 months ago

1.0.0-rc1

12 months ago

1.0.0-rc2

12 months ago

1.0.0-rc3

12 months ago

0.5.2

4 years ago

0.5.1

4 years ago

0.5.0

5 years ago

0.4.0

5 years ago

0.3.0

5 years ago

0.3.1

5 years ago

0.1.6

6 years ago

0.1.5

6 years ago

0.1.4

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago