🤖 Robot

Fast 1kB functional library for creating Finite State Machines

# interpret

Table of Contents

The interpret function takes a machine and creates a service that can send events into the machine, changing its states. A service does not mutate a machine, but rather creates derived machines with the current state set.

import { createMachine, interpret, state, transition } from 'robot3';

const machine = createMachine({
asleep: state(
transition('wake', 'breakfast')
),
breakfast: state()
});

const service = interpret(machine, () => {
if(service.machine.current === 'breakfast') {
console.log('Wake up!');
}
});

// Later
service.send('wake'); // Wake up!

# Arguments

signature: interpret(machine, onChange, event)

These are the arguments to interpret:

# machine

The state machine, created with createMachine to create a new service for.

# onChange

A callback that is called when the machine completes a transition. Even if the transition results in returning to the same state, the onChange callback is still called.

The onChange function is called back with the service.

# event

The third argument event, can be any object. It is passed to the context function like so:

const context = event => ({
foo: event.foo
});

const machine = createMachine({
idle: state()
}, context);

const event = {
foo: 'bar'
};

interpret(machine, service => {
// Do stuff when the service changes.
}, event);

# Service

A service is an object that interprets a machine, keeping track of the current state. Typically you will only really use service.send to send events and service.context to read extended state values (like those captured from form fields or API requests).

# Properties

# machine

An extended version of the machine passed into interpret, contains a current property which is the current state (string name), and a state property which is an object with the name and the state object (as the property value).

# send

The send function is used to send events into the machine:

service.send('wake');

# context

The context for the service is an object that results from the context function when creating the machine, as well as any reducers that have run as a result of state changes.