# Manage State Machines
Learn to add, retrieve, and manage state machines in dotLottie files for interactive Lottie animations using dotlottie-js.

# Manage State Machines

State Machines, a V2 feature in dotLottie, enable interactive Lottie animations. Define states, transitions, and event listeners to control animation playback based on user input or events. `dotlottie-js` packages these configurations within the `.lottie` file.

For the full `addStateMachine()` signature and schema reference, see [`DotLottie.addStateMachine()`](/docs/tools/dotlottie-js/reference/dotlottie-class#addStateMachine).

## 1. Adding State Machines: `dotlottie.addStateMachine()`

Use the [`dotlottie.addStateMachine()`](/docs/tools/dotlottie-js/reference/dotlottie-class#addStateMachine) method.

```javascript
import { DotLottie } from "@dotlottie/dotlottie-js";

async function main() {
  const dotlottie = new DotLottie();

  // Example State Machine JSON — a two-state toggle driven by an Event input
  const stateMachineData = {
    initial: "state_off",
    states: [
      {
        name: "state_off",
        type: "PlaybackState",
        animation: "anim_toggle", // Animation this state controls
        autoplay: true,
        transitions: [{ type: "Transition", toState: "state_on", guards: [{ type: "Event", inputName: "onClick" }] }],
      },
      {
        name: "state_on",
        type: "PlaybackState",
        animation: "anim_toggle",
        segment: "10 20", // Play a specific segment (frame range as a string)
        autoplay: true,
        transitions: [{ type: "Transition", toState: "state_off", guards: [{ type: "Event", inputName: "onClick" }] }],
      },
    ],
    inputs: [{ type: "Event", name: "onClick" }],
    interactions: [{ type: "PointerDown", actions: [{ type: "Fire", inputName: "onClick" }] }],
  };

  dotlottie.addStateMachine({
    id: "sm_toggle_main", // Required: Unique ID for this state machine in the .lottie
    data: stateMachineData, // Required: The state machine JSON data
    name: "Toggle Button Logic", // Optional
  });

  console.log("State machine added.");

  // Remember to build!
  await dotlottie.build();
}
main();
```

**Key `addStateMachine` Options:**

- `id` (string, required): Unique identifier for the state machine within the `.lottie` file.
- `data` (object, required): The `{ initial, states, inputs?, interactions? }` object described in [`addStateMachine()`](/docs/tools/dotlottie-js/reference/dotlottie-class#addStateMachine). `dotlottie-js` validates this shape and throws a `DotLottieError` if it doesn't conform.
- `name` (string, optional): Human-readable name.

During `build()`, state machine data is written to files like `s/<state_machine_id>.json` inside the archive and the manifest is updated.

## 2. Retrieving State Machines

Access added or loaded state machines.

### Accessing all state machines: `dotlottie.stateMachines`

Returns an array of `LottieStateMachine` objects. See [`dotlottie.stateMachines`](/docs/tools/dotlottie-js/reference/dotlottie-class#stateMachines).

```javascript
const allStateMachines = dotlottie.stateMachines;
console.log(`Found ${allStateMachines.length} state machines.`);

allStateMachines.forEach((sm) => {
  console.log(`State Machine ID: ${sm.id}, Name: ${sm.name}`);
  // Access the raw data directly
  console.log(" SM Data:", sm.data);
});
```

### Getting a specific state machine: `dotlottie.getStateMachine(stateMachineId)`

Retrieves a `LottieStateMachine` instance by its `id`. See [`dotlottie.getStateMachine()`](/docs/tools/dotlottie-js/reference/dotlottie-class#getStateMachine).

```javascript
const toggleSM = dotlottie.getStateMachine("sm_toggle_main");
if (toggleSM) {
  console.log(`Retrieved State Machine: ${toggleSM.name}`);
  console.log(" SM Data:", toggleSM.data);
}
```

## 3. Associating State Machines with Animations

State machines control animations by referencing their ID in each `PlaybackState`'s `animation` field within the state machine JSON (`data`).

**Implicit Association:** The link is defined _inside_ the state machine data you provide to `addStateMachine`.

```javascript
// Add animation and then state machines
await dotlottie
  .addAnimation({
    id: "anim_toggle",
    data: toggleAnimationData,
  })
  .addStateMachine({
    id: "starRating",
    name: "Star Rating ⭐",
    data: {
      initial: "global",
      states: [
        {
          name: "global",
          type: "GlobalState",
          transitions: [
            {
              type: "Transition",
              toState: "star_1",
              guards: [
                {
                  type: "Numeric",
                  conditionType: "Equal",
                  inputName: "rating",
                  compareTo: 1,
                },
              ],
            },
            {
              type: "Transition",
              toState: "star_2",
              guards: [
                {
                  type: "Numeric",
                  conditionType: "Equal",
                  inputName: "rating",
                  compareTo: 2,
                },
              ],
            },
            {
              type: "Transition",
              toState: "star_3",
              guards: [
                {
                  type: "Numeric",
                  conditionType: "Equal",
                  inputName: "rating",
                  compareTo: 3,
                },
              ],
            },
            {
              type: "Transition",
              toState: "star_4",
              guards: [
                {
                  type: "Numeric",
                  conditionType: "Equal",
                  inputName: "rating",
                  compareTo: 4,
                },
              ],
            },
            {
              type: "Transition",
              toState: "star_5",
              guards: [
                {
                  type: "Numeric",
                  conditionType: "Equal",
                  inputName: "rating",
                  compareTo: 5,
                },
              ],
            },
          ],
        },
        {
          type: "PlaybackState",
          name: "star_1",
          animation: "",
          autoplay: true,
          segment: "star_1",
          transitions: [],
        },
        {
          type: "PlaybackState",
          name: "star_2",
          animation: "",
          autoplay: true,
          segment: "star_2",
          transitions: [],
        },
        {
          type: "PlaybackState",
          name: "star_3",
          animation: "",
          autoplay: true,
          segment: "star_3",
          transitions: [],
        },
        {
          type: "PlaybackState",
          name: "star_4",
          animation: "",
          autoplay: true,
          segment: "star_4",
          transitions: [],
        },
        {
          type: "PlaybackState",
          name: "star_5",
          animation: "",
          autoplay: true,
          segment: "star_5",
          transitions: [],
        },
      ],
      interactions: [
        {
          type: "PointerDown",
          layerName: "star1",
          actions: [
            {
              type: "SetNumeric",
              inputName: "rating",
              value: 1,
            },
            {
              type: "SetTheme",
              value: "air",
            },
            {
              type: "FireCustomEvent",
              value: "CustomEvent!",
            },
            {
              type: "OpenUrl",
              url: "https://www.lottiefiles.com",
              target: "_blank",
            },
          ],
        },
        {
          type: "PointerDown",
          layerName: "star2",
          actions: [
            {
              type: "SetNumeric",
              inputName: "rating",
              value: 2,
            },
          ],
        },
        {
          type: "PointerDown",
          layerName: "star3",
          actions: [
            {
              type: "SetNumeric",
              inputName: "rating",
              value: 3,
            },
          ],
        },
        {
          type: "PointerDown",
          layerName: "star4",
          actions: [
            {
              type: "SetNumeric",
              inputName: "rating",
              value: 4,
            },
          ],
        },
        {
          type: "PointerDown",
          layerName: "star5",
          actions: [
            {
              type: "SetNumeric",
              inputName: "rating",
              value: 5,
            },
          ],
        },
      ],
      inputs: [
        {
          type: "Numeric",
          name: "rating",
          value: 0,
        },
      ],
    },
  })
  .build();
```

## 4. Removing State Machines: `dotlottie.removeStateMachine(stateMachineId)`

Remove a state machine by its `id`. Returns the `DotLottie` instance for method chaining. See [`dotlottie.removeStateMachine()`](/docs/tools/dotlottie-js/reference/dotlottie-class#removeStateMachine).

```javascript
// Check initial count
const initialSmCount = dotlottie.stateMachines.length;

dotlottie.removeStateMachine("sm_toggle_main");

// Check if count decreased
if (dotlottie.stateMachines.length < initialSmCount) {
  console.log("State Machine 'sm_toggle_main' removed.");
} else {
  console.log("State Machine 'sm_toggle_main' not found or not removed.");
}

// Remember to build!
// await dotlottie.build();
```

State machines are a powerful V2 feature for creating interactive Lottie experiences. `dotlottie-js` packages the logic; the player executes it.

Next up: [Merge Instances](/docs/tools/dotlottie-js/how-to-guides/merge-instances)
