1.0.0 • Published 5 years ago

next-state v1.0.0

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

next-state

Build Status npm node license downloads Coverage Status

Simple event-driven state machine.

Support

Buy Me A Coffee

Install

npm i next-state

Usage

Let's imagine you have 3 states:

INTERMEDIATE -> ACTIVE <-> INACTIVE

You should define 3 transitions:

const { createState, createMachine } = require('next-state');

const INTERMEDIATE = 'INTERMEDIATE';
const ACTIVE = 'ACTIVE';
const INACTIVE = 'INACTIVE';

const transitions = {
  [INTERMEDIATE]: createState(ACTIVE),
  [ACTIVE]: createState(INACTIVE),
  [INACTIVE]: createState(ACTIVE)
};

const machine = createMachine(transitions, INTERMEDIATE);

machine.on(ACTIVE, () => console.log('button pressed on'));
machine.on(INACTIVE, () => console.log('button pressed off'));

function FriendlyButton() {
  return <Button onClick={ () => {
    const nextstate = machine.state === ACTIVE ? INACTIVE : ACTIVE;
    machine.next(nextstate);
  }; }> { machine.state } </Button>
}

See also nodertc/dtls for more complex example.

License

MIT, 2019 © Dmitriy Tsvettsikh