state0

state management

Usage no npm install needed!

<script type="module">
  import state0 from 'https://cdn.skypack.dev/state0';
</script>

README

The ignorant queue-based state management library

Example

Minimal example for how to use state0

import {
  IQueue,
  IStateRecord,
  makeQueue,
  queueDispatch
} from "state0";

const CLICK_ACTION = "CLICK_ACTION";
const CLICK_ROOT = "click";

export interface IClickState {
  amount: number;
}

// Our initial state
export const initialState: IStateRecord<IClickState> = {
  [CLICK_ROOT]: {
    amount: 0,
  },
};

// read-only subscriber.
// a good place to trigger toast notifications etc.
export const clickSubscriber = {
  type: CLICK_ACTION,
  root: CLICK_ROOT,
  id: "onClick",
  trigger: (data: IClickState) => {
    console.log(`Just received some data ${data}`);
  },
};

// read / write reducer
export const clickReducer = {
  type: CLICK_ACTION,
  root: CLICK_ROOT,
  trigger: (prevState: IClickState, nextState: IClickState): IClickState => {
    return { amount: prevState.amount + nextState.amount };
  },
};

const simulateClick = (queue: IQueue<IClickState>) =>
  queueDispatch<IClickState>(queue, {
    type: CLICK_ACTION,
    payload: { amount: 1 },
  });

const queue = makeQueue<IClickState>(
  initialState,
  [clickReducer],
  [clickSubscriber]
);

// simulate some clicks
simulateClick(queue);
simulateClick(queue);
simulateClick(queue);
simulateClick(queue);

Using it with React

Click here

Documentation

How to use it

Installation

To install run

yarn install state0

# or

npm install state0

Then you are ready to use it:

import { makeQueue } from "state0";