# Getting Started

Suppose we want to model a Promise (opens new window) as a state machine. First, install XState using NPM or Yarn:

npm install xstate --save

Then, in your project, import createMachine, which is a factory function that creates a state machine or statechart:

import { createMachine } from 'xstate';

const promiseMachine = createMachine(/* ... */);

We'll pass the machine configuration inside of createMachine(...). Since this is a hierarchical machine, we need to provide the:

  • id - to identify the machine and set the base string for its child state node IDs
  • initial - to specify the initial state node this machine should be in
  • states - to define each of the child states:
import { createMachine } from 'xstate';

const promiseMachine = createMachine({
  id: 'promise',
  initial: 'pending',
  states: {
    pending: {},
    resolved: {},
    rejected: {}
  }
});

Then, we need to add transitions to the state nodes and mark the resolved and rejected state nodes as final state nodes since the promise machine terminates running once it reaches those states:

import { createMachine } from 'xstate';

const promiseMachine = createMachine({
  id: 'promise',
  initial: 'pending',
  states: {
    pending: {
      on: {
        RESOLVE: { target: 'resolved' },
        REJECT: { target: 'rejected' }
      }
    },
    resolved: {
      type: 'final'
    },
    rejected: {
      type: 'final'
    }
  }
});

To interpret the machine and make it run, we need to add an interpreter. This creates a service:

import { createMachine, interpret } from 'xstate';

const promiseMachine = createMachine({
  /* ... */
});

const promiseService = interpret(promiseMachine).onTransition((state) =>
  console.log(state.value)
);

// Start the service
promiseService.start();
// => 'pending'

promiseService.send({ type: 'RESOLVE' });
// => 'resolved'

You can also copy/paste the createMachine(...) code and visualize it on XState Viz (opens new window)—note that you'll have to change createMachine to Machine since the Xstate visualizer uses an older version of Xstate (we're going to update it soon):

Last Updated: 10/26/2021, 6:09:54 PM