DOCS CORE_CONCEPTS robot-hooks

robot-hooks

robot-hooks

The robot-hooks package provides the low-level APIs for building hooks for use with Robot finite state machines that works with any hooks supporting libraries.

If you are using React, Preact, or Haunted, you probably want to use those integrations instead.

Example

import { createMachine, state, transition } from 'robot3';
import { component, useEffect, useState, html } from 'haunted';
import { createUseMachine } from 'robot-hooks';

const useMachine = createUseMachine(useEffect, useState);

const machine = createMachine({
  idle: state(
    transition('click', 'active')
  ),
  active: state()
});

function App() {
  const [current, send] = useMachine(machine);

  return html`
    <button type="button" @click=${() => send('click')}>
      State: ${current.name}
    </button>
  `;
}

customElements.define('my-app', component(App));

Installation

Install robot-hooks via npm or Yarn.

via npm:

npm install robot-hooks robot3 --save

Or Yarn:

yarn add robot-hooks robot3

Usage

At present the robot-hooks library has one export, createUseMachine.

createUseMachine

signature: createUseMachine(useEffect, useState).

The createUseMachine function creates a useMachine hook. It expects 2 hooks from the parent hooks implementation; useEffect and useState. This will work with any hooks library that supports these functions.

useMachine

signature: useMachine(machine, initialContext).

The useMachine hook takes a state machine (and optionally an initial context object) and returns a current object that represents the current state, and a send function.

The send function is the same as documented here; it sends events into the machine.

current is an object with following properties:

  • name: The name of the state.
  • context: The service’s context object, which contains values derived via reducers.
const context = initialContext => ({
  ...initialContext,
  page: 23
});

const machine = createMachine({
  one: state(
    transition('go', 'two')
  ),
  two: state()
}, context);

// ... later

function App() {
  const [current, send] = useMachine(machine, { foo: 'bar' });
  const { page } = current.context;

  console.log(current.name); // "one"
  console.log(page); // 23
}