@xstate/fsm


XState FSM
XState for Finite State Machines

The @xstate/fsm package contains a minimal, 1kb implementation of XState for finite state machines.

Features

@xstate/fsm XState
Finite states
Initial state
Transitions (object)
Transitions (string target)
Delayed transitions
Eventless transitions
Nested states
Parallel states
History states
Final states
Context
Entry actions
Exit actions
Transition actions
Parameterized actions
Transition guards
Parameterized guards
Spawned actors
Invoked actors
  • Finite states (non-nested)
  • Initial state
  • Transitions (object or strings)
  • Context
  • Entry actions
  • Exit actions
  • Transition actions
  • state.changed

If you want to use statechart features such as nested states, parallel states, history states, activities, invoked services, delayed transitions, transient transitions, etc. please use XState.

Super quick start

Installation

  1. npm i @xstate/fsm

Usage (machine):

  1. import { createMachine } from '@xstate/fsm';
  2. const toggleMachine = createMachine({
  3. id: 'toggle',
  4. initial: 'inactive',
  5. states: {
  6. inactive: { on: { TOGGLE: 'active' } },
  7. active: { on: { TOGGLE: 'inactive' } }
  8. }
  9. });
  10. const { initialState } = toggleMachine;
  11. const toggledState = toggleMachine.transition(initialState, 'TOGGLE');
  12. toggledState.value;
  13. const untoggledState = toggleMachine.transition(toggledState, 'TOGGLE');
  14. untoggledState.value;
  15. // => 'inactive'

Usage (service):

  1. import { createMachine, interpret } from '@xstate/fsm';
  2. const toggleMachine = createMachine({});
  3. const toggleService = interpret(toggleMachine).start();
  4. toggleService.subscribe((state) => {
  5. console.log(state.value);
  6. });
  7. toggleService.send('TOGGLE');
  8. toggleService.send('TOGGLE');
  9. toggleService.stop();

API

createMachine(config, options)

Creates a new finite state machine from the config.

Argument Type Description
config object (see below) The config object for creating the machine.
options object (see below) The optional options object.

Returns:

A Machine, which provides:

  • machine.initialState: the machine’s resolved initial state
  • machine.transition(state, event): a pure transition function that returns the next state given the current state and event

The machine config has this schema:

Machine config

  • id (string) - an identifier for the type of machine this is. Useful for debugging.
  • initial (string) - the key of the initial state.
  • states (object) - an object mapping state names (keys) to states

State config

  • on (object) - an object mapping event types (keys) to transitions

Transition config

String syntax:

  • (string) - the state name to transition to.
    • Same as { target: stateName }

Object syntax:

  • target? (string) - the state name to transition to.
  • actions? (Action | Action[]) - the action(s) to execute when this transition is taken.
  • cond? (Guard) - the condition (predicate function) to test. If it returns true, the transition will be taken.

Machine options

  • actions? (object) - a lookup object for your string actions.

Action config

Function syntax:

  • (function) - the action function to execute. Resolves to { type: actionFn.name, exec: actionFn } and the function takes the following arguments:
    1. context (any) - the machine’s current context.
    2. event (object) - the event that caused the action to be executed.

Object syntax:

  • type (string) - the action type.
  • exec? (function) - the action function to execute.

String syntax:

  • (string) - the action type.
    • By default it resolves to { type: actionType, exec: undefined }. It can resolve to resolved function or resolved object action if the action can be looked up in the options.actions object.
Why use a string or object for defining actions? Using the string or object syntax is useful for handling actions in a custom way, rather than baking in the implementation details to your machine: js const nextState = machine.transition(); nextState.actions.forEach((action) => { if (action.type === 'focus') { } });

machine.initialState

The resolved initial state of the machine.

machine.transition(state, event)

A pure transition function that returns the next state given the current state and event.

The state can be a string state name, or a State object (the return type of machine.transition(...)).

Argument Type Description
state string or State object The current state to transition from
event string or { type: string, ... } The event that transitions the current state to the next state

Returns:

A State object, which represents the next state.

Example:

  1. const yellowState = machine.transition('green', 'TIMER');
  2. const redState = machine.transition(yellowState, 'TIMER');
  3. const greenState = machine.transition(yellowState, { type: 'TIMER' });
  4. // => { value: 'green', ... }

State

An object that represents the state of a machine with the following schema:

  • value (string) - the finite state value
  • context (object) - the extended state (context)
  • actions (array) - an array of action objects representing the side-effects (actions) to be executed
  • changed (boolean) - whether this state is changed from the previous state (true if the state.value and state.context are the same, and there are no side-effects)
  • matches(value) (boolean) - whether this state’s value matches (i.e., is equal to) the value. This is useful for typestate checking.

interpret(machine)

Creates an instance of an interpreted machine, also known as a service. This is a stateful representation of the running machine, which you can subscribe to, send events to, start, and stop.

Actions will also be executed by the interpreter.

Argument Type Description
machine StateMachine The machine to be interpreted.

Example:

  1. import { createMachine, interpret } from '@xstate/fsm';
  2. const machine = createMachine({});
  3. const service = interpret(machine);
  4. const subscription = service.subscribe((state) => {
  5. console.log(state);
  6. });
  7. service.start();
  8. service.send('SOME_EVENT');
  9. service.send({ type: 'ANOTHER_EVENT' });
  10. subscription.unsubscribe();
  11. service.stop();

service.subscribe(stateListener)

A service (created from interpret(machine)) can be subscribed to via the .subscribe(...) method. The subscription will be notified of all state changes (including the initial state) and can be unsubscribed.

Argument Type Description
stateListener (state) => void The listener that is called with the interpreted machine’s current state whenever it changes.

Returns:

A subscription object with an unsubscribe method.

service.send(event)

Sends an event to the interpreted machine. The event can be a string (e.g., "EVENT") or an object with a type property (e.g., { type: "EVENT" }).

Argument Type Description
event string or { type: string, ... } The event to be sent to the interpreted machine.

service.start()

Starts the interpreted machine.

Events sent to the interpreted machine will not trigger any transitions until the service is started. All listeners (via service.subscribe(listener)) will receive the machine.initialState.

service.stop()

Stops the interpreted machine.

Events sent to a stopped service will no longer trigger any transitions. All listeners (via service.subscribe(listener)) will be unsubscribed.

TypeScript

A machine can be strictly typed by passing in 3 generic types:

  • TContext - the machine’s context
  • TEvent - all events that the machine accepts
  • TState - all states that the machine can be in

The TContext type should be an object that represents all possible combined types of state.context.

The TEvent type should be the union of all event objects that the machine can accept, where each event object has a { type: string } property, as well as any other properties that may be present.

The TState type should be the union of all typestates (value and contexts) that the machine can be in, where each typestate has:

  • value (string) - the value (name) of the state
  • context (object) - an object that extends TContext and narrows the shape of the context to what it should be in this state.

Example:

  1. interface User {
  2. name: string;
  3. }
  4. interface UserContext {
  5. user?: User;
  6. error?: string;
  7. }
  8. type UserEvent =
  9. | { type: 'FETCH'; id: string }
  10. | { type: 'RESOLVE'; user: User }
  11. | { type: 'REJECT'; error: string };
  12. type UserState =
  13. | {
  14. value: 'idle';
  15. context: UserContext & {
  16. user: undefined;
  17. error: undefined;
  18. };
  19. }
  20. | {
  21. value: 'loading';
  22. context: UserContext;
  23. }
  24. | {
  25. value: 'success';
  26. context: UserContext & { user: User; error: undefined };
  27. }
  28. | {
  29. value: 'failure';
  30. context: UserContext & { user: undefined; error: string };
  31. };
  32. const userMachine = createMachine<UserContext, UserEvent, UserState>({
  33. /* ... */
  34. });
  35. const userService = interpret(userMachine);
  36. userService.subscribe((state) => {
  37. if (state.matches('success')) {
  38. // from UserState, `user` will be defined
  39. state.context.user.name;
  40. }
  41. });

Example

  1. import { createMachine, assign, interpret } from '@xstate/fsm';
  2. const lightMachine = createMachine({
  3. id: 'light',
  4. initial: 'green',
  5. context: { redLights: 0 },
  6. states: {
  7. green: {
  8. on: {
  9. TIMER: 'yellow'
  10. }
  11. },
  12. yellow: {
  13. on: {
  14. TIMER: {
  15. target: 'red',
  16. actions: () => console.log('Going to red!')
  17. }
  18. }
  19. },
  20. red: {
  21. entry: assign({ redLights: (ctx) => ctx.redLights + 1 }),
  22. on: {
  23. TIMER: 'green'
  24. }
  25. }
  26. }
  27. });
  28. const lightService = interpret(lightMachine);
  29. lightService.subscribe((state) => {
  30. console.log(state);
  31. });
  32. lightService.start();
  33. lightService.send('TIMER');
  34. lightService.send('TIMER');
  35. // => logs {
  36. // value: 'red',
  37. // context: { redLights: 1 },
  38. // actions: [],
  39. // changed: true
  40. // }