Introduction
Robot is a small library for building finite state machines. You describe every state your code can be in and the events that move it between them, using nothing but functions. Invalid states can't happen, because they were never described.
Install
Robot is published to npm as robot3. It has no dependencies.
BASH
npm install robot3 Your first machine
A machine is an object of named states. Each state lists the transitions out of it: the event that triggers it, and where it goes.
machine.js JS
import { createMachine, state, transition } from 'robot3';
const machine = createMachine({
inactive: state(
transition('toggle', 'active')
),
active: state(
transition('toggle', 'inactive')
)
});
export default machine; Use it in a component
Robot doesn't render anything itself. Integrations for React, Preact, Svelte, Lit and Haunted connect a machine to your UI.
Toggle.jsx JSX
import { useMachine } from 'react-robot';
import machine from './machine.js';
function Toggle() {
const [current, send] = useMachine(machine);
return (
<button onClick={() => send('toggle')}>
State: {current.name}
</button>
);
} Async work
invoke runs a promise-returning function when a
state is entered and transitions on done or error.
reduce folds the result into the machine's context.
users.js JS
import { createMachine, invoke, reduce, state, transition } from 'robot3';
const context = () => ({ users: [] });
async function loadUsers() {
const res = await fetch('/api/users');
return res.json();
}
const machine = createMachine({
idle: state(
transition('fetch', 'loading')
),
loading: invoke(loadUsers,
transition('done', 'loaded',
reduce((ctx, ev) => ({ ...ctx, users: ev.data }))
),
transition('error', 'idle')
),
loaded: state()
}, context); Where next
01 / Concepts Core concepts States, transitions, events, guards and actions, one at a time. 04 / API API reference Every export, with signatures and examples. 03 / Guides Composition Build machines out of small reusable functions. 03 / Guides Robot vs. XState How the two libraries differ, and when to pick which.