Skip to content

Machine Enhancers

Matchina provides several Machine Enhancers that enhance the usability of state machines while simplifying their interfaces for different use cases. These wrappers include:

  • eventApi: Creates a flat event API for a factory machine
  • addEventApi: Enhances a machine with an api for sending events
  • zen: Mixes an event API into the machine
  • pure: Provides a minimal interface with only the essential methods
const plainFactoryMachine = createMachine(states, transitions, initialState);
plainFactoryMachine.send("someEvent", 1, 2, 3);
const api = eventApi(plainFactoryMachine);
api.someEvent(1, 2, 3);
const zenMachine = assignEventApi(createMachine(states, transitions, initialState));
zenMachine.someEvent(1, 2, 3);
const alsoZen = matchina(states, transitions, initialState);
alsoZen.someEvent(1, 2, 3);
const pureVersion = pure(zenMachine);
pureVersion.send("someEvent", 1, 2, 3);

Use eventApi when:

  • You want to expose a simplified event-sending interface
  • You’re building a public API for your state machine
  • You want fully typed event handlers with proper parameter types

The eventApi function creates a flat event API for a factory machine, simplifying the process of sending events to a machine. This is particularly useful when you want to expose a cleaner interface for transitions without exposing the full machine.

The generated API is fully typed, with the correct parameter types for each event handler:

The addEventApi function enhances a machine by adding an api property that provides a flat event API for sending events. This is useful when you want to keep the original machine intact while providing a simplified interface for event handling.

The addEventApi function is particularly useful when you want to maintain the original machine’s structure while providing a more user-friendly interface for sending events.

The assignEventApi enhancer builds on top of eventApi and provides a clean, minimal interface for working with state machines. It combines the event API with easy access to the machine’s state and change, along with a setup method for integrations.

The assignEventApi enhancer is ideal for React components and other scenarios where you want a simple, unified interface.

However, be careful not to define event names that conflict with the machine’s properties or methods, as this can lead to unexpected behavior. The assignEventApi enhancer does not handle naming conflicts.

The pure wrapper provides the most minimal interface for a state machine, exposing only the essential getState and send methods. This is useful when you want to limit access to the machine’s functionality or when you’re passing the machine to code that only needs these core capabilities.