Section 04 / API Doc_id action Read_time 1 min

action

action takes a function that will be run during a transition. The primary purpose of using action is to perform side-effects.

The function receives the current context and the event. Its return value is ignored and the context passes through unchanged. To update the context, use reduce instead.

Actions can also be passed directly to state, where they run whenever the machine enters that state.

This example triggers an event on an element when transitioning to the next state.

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

function dispatchOn(ctx) {
  const { element } = ctx;
  element.dispatchEvent(new CustomEvent('toggled'));
}

const machine = createMachine({
  on: state(
    transition('toggle', 'off')
  ),
  off: state(
    transition('toggle', 'on',
      action(dispatchOn)
    )
  )
}, () => ({
  element: document.querySelector('#toggler')
}));