Search code examples
javascriptstatestate-managementxstate

How to reuse state transitions in xstate?


Take the following finite-state machine:

const machine = Machine({
  initial: "foo",
  states: {
    foo: {
      on: {
        BAZ: "baz",
        QUX: "qux",
      },
    },
    bar: {
      on: {
        BAZ: "baz",
        QUX: "qux",
      },
    },
    baz: {
      on: {
        FOO: "foo",
        BAR: "bar",
      },
    },
    qux: {
      on: {
        FOO: "foo",
        BAR: "bar",
      },
    },
  },
});

Notice that there are two duplicated sets of state transitions:

on: {
  FOO: "foo",
  bar: "bar",
}
on: {
  BAZ: "baz",
  QUX: "qux",
}

Other than defining the state transitions as good ol' JavaScript objects outside of the Machine definition, is there an idiosyncratic way to do this?


Solution

  • Other than defining the state transitions as good ol' JavaScript objects outside of the Machine definition

    You answered your own question! You already know how to deduplicate this data, so define these as external objects and reference them within the machine. There doesn't need to be a special API to do this.