What are Actions?
Actions are functions that produce side effects but do not return values that affect the machine’s state. Common examples include:- Updating context with
assign - Sending events to actors
- Logging
- Triggering external API calls
- Updating UI
Actions are declarative and executed automatically by the XState interpreter. They should not be called directly in your code.
Entry and Exit Actions
States can define actions that execute when entering or exiting that state.Transition Actions
Actions can be executed as part of a transition, running when the transition is taken.Built-in Actions
XState provides several built-in action creators:import { createMachine, assign } from 'xstate';
const machine = createMachine({
context: {
count: 0,
message: ''
},
on: {
inc: {
actions: assign({
count: ({ context }) => context.count + 1
})
},
updateMessage: {
actions: assign(({ context, event }) => {
return {
message: event.message.trim()
};
})
}
}
});
import { createMachine, raise } from 'xstate';
const machine = createMachine({
initial: 'idle',
states: {
idle: {
on: {
START: {
target: 'running',
actions: raise({ type: 'INTERNAL_START' })
}
}
},
running: {
on: {
INTERNAL_START: {
actions: () => console.log('Machine started!')
}
}
}
}
});
import { createMachine, sendTo, createActor, fromPromise } from 'xstate';
const childActor = fromPromise(async () => {
return { data: 'result' };
});
const machine = createMachine({
initial: 'idle',
states: {
idle: {
on: {
START: {
actions: sendTo('childRef', { type: 'GO' })
}
}
}
}
});
import { createMachine, log } from 'xstate';
const machine = createMachine({
context: { count: 0 },
on: {
EVENT: {
actions: [
log('Event received'),
log(({ context, event }) => ({ context, event }), 'State info')
]
}
}
});
import { createMachine, emit, createActor } from 'xstate';
const machine = createMachine({
on: {
something: {
actions: emit({
type: 'emitted',
some: 'data'
})
}
}
});
const actor = createActor(machine).start();
actor.on('emitted', (event) => {
console.log(event);
// { type: 'emitted', some: 'data' }
});
actor.send({ type: 'something' });
Multiple Actions
You can execute multiple actions in sequence by providing an array:Dynamic Actions with enqueueActions
For conditional or dynamic action execution, useenqueueActions:
Named Actions
For reusability and testability, define actions separately and reference them by name:Action Arguments
All actions receive anargs object with:
context- The current machine contextevent- The event that triggered the transitionself- A reference to the current actorsystem- The actor system