Skip to main content

Defining Action Handlers

Action handlers are functions triggered when an action is called and its transition is executed.
They are the place to run business logic, perform state updates, or handle side effects like API calls.


🧠 Handler Signature

Each handler receives an object with:

  • ctx: current context (state, sv, ref)
  • done: callback to signal completion
  • payload: optional action input

Basic Example

const actionHandlers = {
increment: async ({ ctx, done, payload }) => {
ctx.state.count++;
done();
},
};

⏳ Async Support

All handlers can be async. You must call done() when finished:

const actionHandlers = {
fetchData: async ({ ctx, done }) => {
const res = await fetch('/api/data');
ctx.state.data = await res.json();
done();
},
};

📌 Best Practices

  • Always call done() — or your machine will "hang"
  • Keep side effects deterministic and predictable
  • Access and update context values via ctx.state, ctx.sv, etc.

📎 Optional: Action payloads

You can also define handlers that use payload values:

increment: async ({ ctx, payload, done }) => {
ctx.state.count += payload.step || 1;
done();
};

🔗 Where to define

Action handlers are passed to createMachineConfig():

createMachineConfig({
...actionHandlers,
});