xstate
- Version 5.18.1
- Published
- 1.66 MB
- No dependencies
- MIT license
Install
npm i xstate
yarn add xstate
pnpm add xstate
Overview
Finite State Machines and Statecharts for the Modern Web.
Index
Variables
Functions
- and()
- assertEvent()
- assign()
- cancel()
- createActor()
- createEmptyActor()
- createMachine()
- emit()
- enqueueActions()
- forwardTo()
- fromCallback()
- fromEventObservable()
- fromObservable()
- fromPromise()
- fromTransition()
- getInitialSnapshot()
- getNextSnapshot()
- getStateNodes()
- isMachineSnapshot()
- log()
- matchesState()
- not()
- or()
- pathToStateValue()
- raise()
- sendParent()
- sendTo()
- setup()
- spawnChild()
- stateIn()
- stopChild()
- toObserver()
- toPromise()
- waitFor()
Classes
Interfaces
Enums
Type Aliases
- Action
- ActionFunction
- ActionFunctionMap
- Actions
- ActorLogicFrom
- ActorRefFrom
- ActorRefFromLogic
- ActorRefLike
- AnyActor
- AnyActorLogic
- AnyActorRef
- AnyActorScope
- AnyFunction
- AnyHistoryValue
- AnyInterpreter
- AnyInvokeConfig
- AnyMachineSnapshot
- AnyState
- AnyStateConfig
- AnyStateMachine
- AnyStateNode
- AnyStateNodeConfig
- AnyStateNodeDefinition
- AnyTransitionConfig
- AnyTransitionDefinition
- Assigner
- CallbackActorLogic
- CallbackActorRef
- CallbackLogicFunction
- CallbackSnapshot
- Cast
- Compute
- ConditionalRequired
- ContextFactory
- ContextFrom
- DelayConfig
- DelayedTransitions
- DelayExpr
- DelayFunctionMap
- DevToolsAdapter
- DoNotInfer
- Elements
- EmittedFrom
- Equals
- EventDescriptor
- EventFrom
- EventFromLogic
- EventObject
- ExtractEvent
- GetConcreteByKey
- GetParameterizedParams
- HistoryValue
- HomomorphicOmit
- HomomorphicPick
- Identity
- IndexByProp
- IndexByType
- InferEvent
- InputFrom
- InspectionEvent
- InternalMachineImplementations
- Interpreter
- InterpreterFrom
- Invert
- InvokeConfig
- IsAny
- IsLiteralString
- IsNever
- IsNotNever
- Lazy
- LogExpr
- LowInfer
- MachineConfig
- MachineContext
- MachineImplementationsFrom
- MachineSnapshot
- Mapper
- MaybeLazy
- Merge
- MetaObject
- NoInfer
- NonReducibleUnknown
- NoRequiredParams
- ObservableActorLogic
- ObservableActorRef
- ObservableSnapshot
- Observer
- OutputFrom
- PartialAssigner
- PromiseActorLogic
- PromiseActorRef
- PromiseSnapshot
- Prop
- PropertyAssigner
- RequiredActorOptions
- RequiredActorOptionsKeys
- SendExpr
- SimpleOrStateNodeConfig
- SingleOrArray
- Snapshot
- SnapshotFrom
- SnapshotStatus
- Spawner
- StateFrom
- StateId
- StateKey
- StateNodesConfig
- StateSchema
- StatesConfig
- StatesDefinition
- StateTypes
- StateValue
- StateValueFrom
- TagsFrom
- ToChildren
- TODO
- ToStateValue
- TransitionActorLogic
- TransitionActorRef
- TransitionConfigOrTarget
- TransitionConfigTarget
- TransitionDefinitionMap
- Transitions
- TransitionsConfig
- TransitionSnapshot
- TransitionTarget
- UnknownAction
- UnknownActorLogic
- UnknownActorRef
- UnknownMachineConfig
- Values
- WithDynamicParams
Variables
variable interpret
const interpret: <TLogic extends AnyActorLogic>( logic: TLogic, ...[options]: ConditionalRequired< [ options?: ActorOptions<TLogic> & { [K in RequiredActorOptionsKeys<TLogic>]: unknown; } ], IsNotNever<RequiredActorOptionsKeys<TLogic>> >) => Actor<TLogic>;
Creates a new Interpreter instance for the given machine with the provided options, if any.
Deprecated
Use
createActor
instead
variable stop
const stop: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TEvent extends EventObject>( actorRef: ResolvableActorRef<TContext, TExpressionEvent, TParams, TEvent>) => StopAction<TContext, TExpressionEvent, TParams, TEvent>;
Stops a child actor.
Deprecated
Use
stopChild(...)
instead
Functions
function and
and: < TContext extends MachineContext, TExpressionEvent extends EventObject, TArg extends unknown[]>( guards: readonly [ ...{ [K in keyof TArg]: SingleGuardArg< TContext, TExpressionEvent, unknown, TArg[K] >; } ]) => GuardPredicate< TContext, TExpressionEvent, unknown, NormalizeGuardArgArray<DoNotInfer<TArg>>>;
Higher-order guard that evaluates to
true
if allguards
passed to it evaluate totrue
.Guards
Returns
A guard action object
Example 1
import { setup, and } from 'xstate';const machine = setup({guards: {someNamedGuard: () => true}}).createMachine({on: {someEvent: {guard: and([({ context }) => context.value > 0, 'someNamedGuard']),actions: () => {// will be executed if all guards in `and(...)`// evaluate to true}}}});
function assertEvent
assertEvent: <TEvent extends EventObject, TAssertedType extends TEvent['type']>( event: TEvent, type: TAssertedType | TAssertedType[]) => asserts event is TEvent & { type: TAssertedType };
Asserts that the given event object is of the specified type or types. Throws an error if the event object is not of the specified types.
Example 1
// ...entry: ({ event }) => {assertEvent(event, 'doNothing');// event is { type: 'doNothing' }},// ...exit: ({ event }) => {assertEvent(event, 'greet');// event is { type: 'greet'; message: string }assertEvent(event, ['greet', 'notify']);// event is { type: 'greet'; message: string }// or { type: 'notify'; message: string; level: 'info' | 'error' }},
function assign
assign: < TContext extends MachineContext, TExpressionEvent extends AnyEventObject, TParams extends {}, TEvent extends EventObject, TActor extends ProvidedActor>( assignment: | Assigner<LowInfer<TContext>, TExpressionEvent, TParams, TEvent, TActor> | PropertyAssigner< LowInfer<TContext>, TExpressionEvent, TParams, TEvent, TActor >) => ActionFunction< TContext, TExpressionEvent, TEvent, TParams, TActor, never, never, never, never>;
Updates the current context of the machine.
Parameter assignment
An object that represents the partial context to update, or a function that returns an object that represents the partial context to update.
Example 1
import { createMachine, assign } from 'xstate';const countMachine = createMachine({context: {count: 0,message: ''},on: {inc: {actions: assign({count: ({ context }) => context.count + 1})},updateMessage: {actions: assign(({ context, event }) => {return {message: event.message.trim()};})}}});
function cancel
cancel: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TEvent extends EventObject>( sendId: ResolvableSendId<TContext, TExpressionEvent, TParams, TEvent>) => CancelAction<TContext, TExpressionEvent, TParams, TEvent>;
Cancels a delayed
sendTo(...)
action that is waiting to be executed. The canceledsendTo(...)
action will not send its event or execute, unless thedelay
has already elapsed beforecancel(...)
is called.Parameter sendId
The
id
of thesendTo(...)
action to cancel.Example 1
import { createMachine, sendTo, cancel } from 'xstate';const machine = createMachine({// ...on: {sendEvent: {actions: sendTo('some-actor',{ type: 'someEvent' },{id: 'some-id',delay: 1000})},cancelEvent: {actions: cancel('some-id')}}});
function createActor
createActor: <TLogic extends AnyActorLogic>( logic: TLogic, ...[options]: ConditionalRequired< [ options?: ActorOptions<TLogic> & { [K in RequiredActorOptionsKeys<TLogic>]: unknown; } ], IsNotNever<RequiredActorOptionsKeys<TLogic>> >) => Actor<TLogic>;
Creates a new actor instance for the given actor logic with the provided options, if any.
Parameter logic
The actor logic to create an actor from. For a state machine actor logic creator, see createMachine. Other actor logic creators include fromCallback, fromEventObservable, fromObservable, fromPromise, and fromTransition.
Parameter options
Actor options
Remarks
When you create an actor from actor logic via
createActor(logic)
, you implicitly create an actor system where the created actor is the root actor. Any actors spawned from this root actor and its descendants are part of that actor system.Example 1
import { createActor } from 'xstate';import { someActorLogic } from './someActorLogic.ts';// Creating the actor, which implicitly creates an actor system with itself as the root actorconst actor = createActor(someActorLogic);actor.subscribe((snapshot) => {console.log(snapshot);});// Actors must be started by calling `actor.start()`, which will also start the actor system.actor.start();// Actors can receive eventsactor.send({ type: 'someEvent' });// You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.actor.stop();
function createEmptyActor
createEmptyActor: () => ActorRef< Snapshot<undefined>, AnyEventObject, AnyEventObject>;
function createMachine
createMachine: < TContext extends MachineContext, TEvent extends AnyEventObject, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string, TTag extends string, TInput, TOutput extends {}, TEmitted extends EventObject, TMeta extends MetaObject, _ = any>( config: { types?: MachineTypes< TContext, TEvent, TActor, TAction, TGuard, TDelay, TTag, TInput, TOutput, TEmitted, TMeta >; schemas?: unknown; } & MachineConfig< TContext, TEvent, TActor, TAction, TGuard, TDelay, TTag, TInput, TOutput, TEmitted, TMeta >, implementations?: InternalMachineImplementations< ResolvedStateMachineTypes< TContext, TEvent, TActor, TAction, TGuard, TDelay, TTag, TEmitted > >) => StateMachine< TContext, TEvent, Cast<ToChildren<TActor>, Record<string, AnyActorRef | undefined>>, TActor, TAction, TGuard, TDelay, StateValue, TTag & string, TInput, TOutput, TEmitted, TMeta, TODO>;
Creates a state machine (statechart) with the given configuration.
The state machine represents the pure logic of a state machine actor.
Parameter config
The state machine configuration.
Parameter options
DEPRECATED: use
setup({ ... })
ormachine.provide({ ... })
to provide machine implementations instead.Example 1
import { createMachine } from 'xstate';const lightMachine = createMachine({id: 'light',initial: 'green',states: {green: {on: {TIMER: { target: 'yellow' }}},yellow: {on: {TIMER: { target: 'red' }}},red: {on: {TIMER: { target: 'green' }}}}});const lightActor = createActor(lightMachine);lightActor.start();lightActor.send({ type: 'TIMER' });
function emit
emit: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TEvent extends EventObject, TEmitted extends AnyEventObject>( eventOrExpr: | DoNotInfer<TEmitted> | SendExpr<TContext, TExpressionEvent, TParams, DoNotInfer<TEmitted>, TEvent>) => ActionFunction< TContext, TExpressionEvent, TEvent, TParams, never, never, never, never, TEmitted>;
Emits an event to event handlers registered on the actor via `actor.on(event, handler)`.
Example 1
import { emit } 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);});actor.send({ type: 'something' });// logs:// {// type: 'emitted',// some: 'data'// }
function enqueueActions
enqueueActions: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TEvent extends EventObject = TExpressionEvent, TActor extends ProvidedActor = ProvidedActor, TAction extends ParameterizedObject = ParameterizedObject, TGuard extends ParameterizedObject = ParameterizedObject, TDelay extends string = never, TEmitted extends EventObject = EventObject>( collect: CollectActions< TContext, TExpressionEvent, TParams, TEvent, TActor, TAction, TGuard, TDelay, TEmitted >) => ActionFunction< TContext, TExpressionEvent, TEvent, TParams, TActor, TAction, TGuard, TDelay, TEmitted>;
Creates an action object that will execute actions that are queued by the
enqueue(action)
function.Example 1
import { createMachine, enqueueActions } from 'xstate';const machine = createMachine({entry: enqueueActions(({ enqueue, check }) => {enqueue.assign({ count: 0 });if (check('someGuard')) {enqueue.assign({ count: 1 });}enqueue('someAction');})});
function forwardTo
forwardTo: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TEvent extends EventObject, TDelay extends string = never, TUsedDelay extends TDelay = never>( target: Target<TContext, TExpressionEvent, TParams, TEvent>, options?: SendToActionOptions< TContext, TExpressionEvent, TParams, TEvent, TUsedDelay >) => ActionFunction< TContext, TExpressionEvent, TEvent, TParams, never, never, never, TDelay, never>;
Forwards (sends) an event to the
target
actor.Parameter target
The target actor to forward the event to.
Parameter options
Options to pass into the send action creator.
function fromCallback
fromCallback: < TEvent extends EventObject, TInput = {}, TEmitted extends EventObject = EventObject>( callback: CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>) => CallbackActorLogic<TEvent, TInput, TEmitted>;
An actor logic creator which returns callback logic as defined by a callback function.
Parameter callback
The callback function used to describe the callback logic The callback function is passed an object with the following properties:
-
receive
- A function that can send events back to the parent actor; the listener is then called whenever events are received by the callback actor -sendBack
- A function that can send events back to the parent actor -input
- Data that was provided to the callback actor -self
- The parent actor of the callback actor -system
- The actor system to which the callback actor belongs The callback function can (optionally) return a cleanup function, which is called when the actor is stopped.Returns
Callback logic
Remarks
Useful for subscription-based or other free-form logic that can send events back to the parent actor.
Actors created from callback logic (“callback actors”) can:
- Receive events via the
receive
function - Send events to the parent actor via thesendBack
functionCallback actors are a bit different from other actors in that they:
- Do not work with
onDone
- Do not produce a snapshot using.getSnapshot()
- Do not emit values when used with.subscribe()
- Can not be stopped with.stop()
Example 1
const callbackLogic = fromCallback(({ sendBack, receive }) => {let lockStatus = 'unlocked';const handler = (event) => {if (lockStatus === 'locked') {return;}sendBack(event);};receive((event) => {if (event.type === 'lock') {lockStatus = 'locked';} else if (event.type === 'unlock') {lockStatus = 'unlocked';}});document.body.addEventListener('click', handler);return () => {document.body.removeEventListener('click', handler);};});See Also
CallbackLogicFunction for more information about the callback function and its object argument
Input docs for more information about how input is passed
function fromEventObservable
fromEventObservable: < TEvent extends EventObject, TInput extends {}, TEmitted extends EventObject = EventObject>( lazyObservable: ({ input, system, self, emit, }: { input: TInput; system: AnyActorSystem; self: ObservableActorRef<TEvent>; emit: (emitted: TEmitted) => void; }) => Subscribable<TEvent>) => ObservableActorLogic<TEvent, TInput, TEmitted>;
Creates event observable logic that listens to an observable that delivers event objects.
Event observable actor logic is described by an observable stream of event objects. Actors created from event observable logic (“event observable actors”) can:
- Implicitly send events to its parent actor - Emit snapshots of its emitted event objects
Sending events to event observable actors will have no effect.
Parameter lazyObservable
A function that creates an observable that delivers event objects. It receives one argument, an object with the following properties:
-
input
- Data that was provided to the event observable actor -self
- The parent actor -system
- The actor system to which the event observable actor belongs.It should return a Subscribable, which is compatible with an RxJS Observable, although RxJS is not required to create them.
Example 1
import {fromEventObservable,Subscribable,EventObject,createMachine,createActor} from 'xstate';import { fromEvent } from 'rxjs';const mouseClickLogic = fromEventObservable(() => fromEvent(document.body, 'click') as Subscribable<EventObject>);const canvasMachine = createMachine({invoke: {// Will send mouse `click` events to the canvas actorsrc: mouseClickLogic}});const canvasActor = createActor(canvasMachine);canvasActor.start();
function fromObservable
fromObservable: < TContext, TInput extends {}, TEmitted extends EventObject = EventObject>( observableCreator: ({ input, system, self, }: { input: TInput; system: AnyActorSystem; self: ObservableActorRef<TContext>; emit: (emitted: TEmitted) => void; }) => Subscribable<TContext>) => ObservableActorLogic<TContext, TInput, TEmitted>;
Observable actor logic is described by an observable stream of values. Actors created from observable logic (“observable actors”) can:
- Emit snapshots of the observable’s emitted value
The observable’s emitted value is used as its observable actor’s
context
.Sending events to observable actors will have no effect.
Parameter observableCreator
A function that creates an observable. It receives one argument, an object with the following properties:
-
input
- Data that was provided to the observable actor -self
- The parent actor -system
- The actor system to which the observable actor belongsIt should return a Subscribable, which is compatible with an RxJS Observable, although RxJS is not required to create them.
Example 1
import { fromObservable, createActor } from 'xstate';import { interval } from 'rxjs';const logic = fromObservable((obj) => interval(1000));const actor = createActor(logic);actor.subscribe((snapshot) => {console.log(snapshot.context);});actor.start();// At every second:// Logs 0// Logs 1// Logs 2// ...See Also
https://rxjs.dev for documentation on RxJS Observable and observable creators.
Subscribable interface in XState, which is based on and compatible with RxJS Observable.
function fromPromise
fromPromise: <TOutput, TInput = {}, TEmitted extends EventObject = EventObject>( promiseCreator: ({ input, system, self, signal, emit, }: { input: TInput; system: AnyActorSystem; self: PromiseActorRef<TOutput>; signal: AbortSignal; emit: (emitted: TEmitted) => void; }) => PromiseLike<TOutput>) => PromiseActorLogic<TOutput, TInput, TEmitted>;
An actor logic creator which returns promise logic as defined by an async process that resolves or rejects after some time.
Actors created from promise actor logic (“promise actors”) can:
- Emit the resolved value of the promise - Output the resolved value of the promise
Sending events to promise actors will have no effect.
Parameter promiseCreator
A function which returns a Promise, and accepts an object with the following properties:
-
input
- Data that was provided to the promise actor -self
- The parent actor of the promise actor -system
- The actor system to which the promise actor belongsExample 1
const promiseLogic = fromPromise(async () => {const result = await fetch('https://example.com/...').then((data) =>data.json());return result;});const promiseActor = createActor(promiseLogic);promiseActor.subscribe((snapshot) => {console.log(snapshot);});promiseActor.start();// => {// output: undefined,// status: 'active'// ...// }// After promise resolves// => {// output: { ... },// status: 'done',// ...// }See Also
Input docs for more information about how input is passed
function fromTransition
fromTransition: < TContext, TEvent extends EventObject, TSystem extends AnyActorSystem, TInput extends {}, TEmitted extends EventObject = EventObject>( transition: ( snapshot: TContext, event: TEvent, actorScope: ActorScope< TransitionSnapshot<TContext>, TEvent, TSystem, TEmitted > ) => TContext, initialContext: | TContext | (({ input, self, }: { input: TInput; self: TransitionActorRef<TContext, TEvent>; }) => TContext)) => TransitionActorLogic<TContext, TEvent, TInput, TEmitted>;
Returns actor logic given a transition function and its initial state.
A “transition function” is a function that takes the current
state
and receivedevent
object as arguments, and returns the next state, similar to a reducer.Actors created from transition logic (“transition actors”) can:
- Receive events - Emit snapshots of its state
The transition function’s
state
is used as its transition actor’scontext
.Note that the "state" for a transition function is provided by the initial state argument, and is not the same as the State object of an actor or a state within a machine configuration.
Parameter transition
The transition function used to describe the transition logic. It should return the next state given the current state and event. It receives the following arguments:
-
state
- the current state. -event
- the received event. -actorScope
- the actor scope object, with properties likeself
andsystem
.Parameter initialContext
The initial state of the transition function, either an object representing the state, or a function which returns a state object. If a function, it will receive as its only argument an object with the following properties:
-
input
- theinput
provided to its parent transition actor. -self
- a reference to its parent transition actor.Returns
Actor logic
Example 1
const transitionLogic = fromTransition((state, event) => {if (event.type === 'increment') {return {...state,count: state.count + 1};}return state;},{ count: 0 });const transitionActor = createActor(transitionLogic);transitionActor.subscribe((snapshot) => {console.log(snapshot);});transitionActor.start();// => {// status: 'active',// context: { count: 0 },// ...// }transitionActor.send({ type: 'increment' });// => {// status: 'active',// context: { count: 1 },// ...// }See Also
Input docs for more information about how input is passed
function getInitialSnapshot
getInitialSnapshot: <T extends AnyActorLogic>( actorLogic: T, ...[input]: undefined extends InputFrom<T> ? [input?: InputFrom<T>] : [input: InputFrom<T>]) => SnapshotFrom<T>;
function getNextSnapshot
getNextSnapshot: <T extends AnyActorLogic>( actorLogic: T, snapshot: SnapshotFrom<T>, event: EventFromLogic<T>) => SnapshotFrom<T>;
Determines the next snapshot for the given
actorLogic
based on the givensnapshot
andevent
.If the
snapshot
isundefined
, the initial snapshot of theactorLogic
is used.Example 1
import { getNextSnapshot } from 'xstate';import { trafficLightMachine } from './trafficLightMachine.ts';const nextSnapshot = getNextSnapshot(trafficLightMachine, // actor logicundefined, // snapshot (or initial state if undefined){ type: 'TIMER' }); // event objectconsole.log(nextSnapshot.value);// => 'yellow'const nextSnapshot2 = getNextSnapshot(trafficLightMachine, // actor logicnextSnapshot, // snapshot{ type: 'TIMER' }); // event objectconsole.log(nextSnapshot2.value);// =>'red'
function getStateNodes
getStateNodes: <TContext extends MachineContext, TEvent extends EventObject>( stateNode: AnyStateNode, stateValue: StateValue) => Array<AnyStateNode>;
Returns the state nodes represented by the current state value.
Parameter stateValue
The state value or State instance
function isMachineSnapshot
isMachineSnapshot: <TContext extends MachineContext, TEvent extends EventObject>( value: unknown) => value is AnyMachineSnapshot;
function log
log: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TEvent extends EventObject>( value?: ResolvableLogValue<TContext, TExpressionEvent, TParams, TEvent>, label?: string) => LogAction<TContext, TExpressionEvent, TParams, TEvent>;
Parameter expr
The expression function to evaluate which will be logged. Takes in 2 arguments:
-
ctx
- the current state context -event
- the event that caused this action to be executed.Parameter label
The label to give to the logged expression.
function matchesState
matchesState: (parentStateId: StateValue, childStateId: StateValue) => boolean;
function not
not: < TContext extends MachineContext, TExpressionEvent extends EventObject, TArg>( guard: SingleGuardArg<TContext, TExpressionEvent, unknown, TArg>) => GuardPredicate< TContext, TExpressionEvent, unknown, NormalizeGuardArg<DoNotInfer<TArg>>>;
Higher-order guard that evaluates to
true
if theguard
passed to it evaluates tofalse
.Guards
Returns
A guard
Example 1
import { setup, not } from 'xstate';const machine = setup({guards: {someNamedGuard: () => false}}).createMachine({on: {someEvent: {guard: not('someNamedGuard'),actions: () => {// will be executed if guard in `not(...)`// evaluates to `false`}}}});
function or
or: < TContext extends MachineContext, TExpressionEvent extends EventObject, TArg extends unknown[]>( guards: readonly [ ...{ [K in keyof TArg]: SingleGuardArg< TContext, TExpressionEvent, unknown, TArg[K] >; } ]) => GuardPredicate< TContext, TExpressionEvent, unknown, NormalizeGuardArgArray<DoNotInfer<TArg>>>;
Higher-order guard that evaluates to
true
if any of theguards
passed to it evaluate totrue
.Guards
Returns
A guard action object
Example 1
import { setup, or } from 'xstate';const machine = setup({guards: {someNamedGuard: () => true}}).createMachine({on: {someEvent: {guard: or([({ context }) => context.value > 0, 'someNamedGuard']),actions: () => {// will be executed if any of the guards in `or(...)`// evaluate to true}}}});
function pathToStateValue
pathToStateValue: (statePath: string[]) => StateValue;
function raise
raise: < TContext extends MachineContext, TExpressionEvent extends EventObject, TEvent extends EventObject, TParams extends {}, TDelay extends string = never, TUsedDelay extends TDelay = never>( eventOrExpr: | DoNotInfer<TEvent> | SendExpr<TContext, TExpressionEvent, TParams, DoNotInfer<TEvent>, TEvent>, options?: RaiseActionOptions< TContext, TExpressionEvent, TParams, DoNotInfer<TEvent>, TUsedDelay >) => ActionFunction< TContext, TExpressionEvent, TEvent, TParams, never, never, never, TDelay, never>;
Raises an event. This places the event in the internal event queue, so that the event is immediately consumed by the machine in the current step.
Parameter eventType
The event to raise.
function sendParent
sendParent: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TSentEvent extends EventObject = AnyEventObject, TEvent extends EventObject = AnyEventObject, TDelay extends string = never, TUsedDelay extends TDelay = never>( event: | TSentEvent | SendExpr<TContext, TExpressionEvent, TParams, TSentEvent, TEvent>, options?: SendToActionOptions< TContext, TExpressionEvent, TParams, TEvent, TUsedDelay >) => ActionFunction< TContext, TExpressionEvent, TEvent, TParams, never, never, never, TDelay, never>;
Sends an event to this machine's parent.
Parameter event
The event to send to the parent machine.
Parameter options
Options to pass into the send event.
function sendTo
sendTo: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TTargetActor extends AnyActorRef, TEvent extends EventObject, TDelay extends string = never, TUsedDelay extends TDelay = never>( to: | string | TTargetActor | (( args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams ) => TTargetActor | string), eventOrExpr: | EventFrom<TTargetActor> | SendExpr< TContext, TExpressionEvent, TParams, InferEvent<Cast<EventFrom<TTargetActor>, EventObject>>, TEvent >, options?: SendToActionOptions< TContext, TExpressionEvent, TParams, DoNotInfer<TEvent>, TUsedDelay >) => ActionFunction< TContext, TExpressionEvent, TEvent, TParams, never, never, never, TDelay, never>;
Sends an event to an actor.
Parameter actor
The
ActorRef
to send the event to.Parameter event
The event to send, or an expression that evaluates to the event to send
Parameter options
Send action options
-
id
- The unique send event identifier (used withcancel()
). -delay
- The number of milliseconds to delay the sending of the event.
function setup
setup: < TContext extends MachineContext, TEvent extends AnyEventObject, TActors extends Record<string, UnknownActorLogic> = {}, TChildrenMap extends Record<string, string> = {}, TActions extends Record<string, {}> = {}, TGuards extends Record<string, {}> = {}, TDelay extends string = never, TTag extends string = string, TInput = {}, TOutput extends {} = {}, TEmitted extends EventObject = EventObject, TMeta extends MetaObject = MetaObject>({ schemas, actors, actions, guards, delays,}: { schemas?: unknown; types?: SetupTypes< TContext, TEvent, TChildrenMap, TTag, TInput, TOutput, TEmitted, TMeta >; actors?: { [K in keyof TActors | Values<TChildrenMap>]: K extends keyof TActors ? TActors[K] : never; }; actions?: { [K in keyof TActions]: ActionFunction< TContext, TEvent, TEvent, TActions[K], ToProvidedActor<TChildrenMap, TActors>, ToParameterizedObject<TActions>, ToParameterizedObject<TGuards>, TDelay, TEmitted >; }; guards?: { [K in keyof TGuards]: GuardPredicate< TContext, TEvent, TGuards[K], ToParameterizedObject<TGuards> >; }; delays?: { [K in TDelay]: DelayConfig< TContext, TEvent, ToParameterizedObject<TActions>['params'], TEvent >; };} & { [K in RequiredSetupKeys<TChildrenMap>]: unknown }) => { createMachine: () => const;};
function spawnChild
spawnChild: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TEvent extends EventObject, TActor extends ProvidedActor>( ...[src, { id, systemId, input, syncSnapshot }]: SpawnArguments< TContext, TExpressionEvent, TEvent, TActor >) => ActionFunction< TContext, TExpressionEvent, TEvent, TParams, TActor, never, never, never, never>;
function stateIn
stateIn: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}>( stateValue: StateValue) => GuardPredicate<TContext, TExpressionEvent, TParams, any>;
function stopChild
stopChild: < TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends {}, TEvent extends EventObject>( actorRef: ResolvableActorRef<TContext, TExpressionEvent, TParams, TEvent>) => StopAction<TContext, TExpressionEvent, TParams, TEvent>;
Stops a child actor.
Parameter actorRef
The actor to stop.
function toObserver
toObserver: <T>( nextHandler?: Observer<T> | ((value: T) => void), errorHandler?: (error: any) => void, completionHandler?: () => void) => Observer<T>;
function toPromise
toPromise: <T extends AnyActorRef>(actor: T) => Promise<OutputFrom<T>>;
Returns a promise that resolves to the
output
of the actor when it is done.Example 1
const machine = createMachine({// ...output: {count: 42}});const actor = createActor(machine);actor.start();const output = await toPromise(actor);console.log(output);// logs { count: 42 }
function waitFor
waitFor: <TActorRef extends AnyActorRef>( actorRef: TActorRef, predicate: (emitted: SnapshotFrom<TActorRef>) => boolean, options?: Partial<WaitForOptions>) => Promise<SnapshotFrom<TActorRef>>;
Subscribes to an actor ref and waits for its emitted value to satisfy a predicate, and then resolves with that value. Will throw if the desired state is not reached after an optional timeout. (defaults to Infinity).
Parameter actorRef
The actor ref to subscribe to
Parameter predicate
Determines if a value matches the condition to wait for
Parameter options
Returns
A promise that eventually resolves to the emitted value that matches the condition
Example 1
const state = await waitFor(someService, (state) => {return state.hasTag('loaded');});state.hasTag('loaded'); // true
Classes
class Actor
class Actor<TLogic extends AnyActorLogic> implements ActorRef< SnapshotFrom<TLogic>, EventFromLogic<TLogic>, EmittedFrom<TLogic> > {}
An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.
constructor
constructor( logic: ActorLogic<any, any, any, any, any>, options?: ActorOptions<TLogic>);
Creates a new actor instance for the given logic with the provided options, if any.
Parameter logic
The logic to create an actor from
Parameter options
Actor options
property clock
clock: Clock;
The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
property id
id: string;
The unique identifier for this actor relative to its parent.
property logic
logic: ActorLogic<any, any, any, any, any>;
property options
options: Readonly<ActorOptions<TLogic>>;
property ref
ref: ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>, EmittedFrom<TLogic>>;
property sessionId
sessionId: string;
The globally unique process ID for this invocation.
property src
src: string | AnyActorLogic;
property system
system: AnyActorSystem;
The system to which this actor belongs.
method [symbolObservable]
[symbolObservable]: () => InteropSubscribable<SnapshotFrom<TLogic>>;
method getPersistedSnapshot
getPersistedSnapshot: () => Snapshot<unknown>;
Obtain the internal state of the actor, which can be persisted.
Remarks
The internal state can be persisted from any actor, not only machines.
Note that the persisted state is not the same as the snapshot from Actor.getSnapshot. Persisted state represents the internal state of the actor, while snapshots represent the actor's last emitted value.
Can be restored with ActorOptions.state
See Also
https://stately.ai/docs/persistence
method getSnapshot
getSnapshot: () => SnapshotFrom<TLogic>;
Read an actor’s snapshot synchronously.
Remarks
The snapshot represent an actor's last emitted value.
When an actor receives an event, its internal state may change. An actor may emit a snapshot when a state transition occurs.
Note that some actors, such as callback actors generated with
fromCallback
, will not emit snapshots.See Also
Actor.subscribe to subscribe to an actor’s snapshot values.
Actor.getPersistedSnapshot to persist the internal state of an actor (which is more than just a snapshot).
method on
on: <TType extends EmittedFrom<TLogic>['type'] | '*'>( type: TType, handler: ( emitted: EmittedFrom<TLogic> & (TType extends '*' ? {} : { type: TType }) ) => void) => Subscription;
method send
send: (event: EventFromLogic<TLogic>) => void;
Sends an event to the running Actor to trigger a transition.
Parameter event
The event to send
method start
start: () => this;
Starts the Actor from the initial state
method stop
stop: () => this;
Stops the Actor and unsubscribe all listeners.
method subscribe
subscribe: { (observer: Observer<SnapshotFrom<TLogic>>): Subscription; ( nextListener?: (snapshot: SnapshotFrom<TLogic>) => void, errorListener?: (error: any) => void, completeListener?: () => void ): Subscription;};
Subscribe an observer to an actor’s snapshot values.
Parameter observer
Either a plain function that receives the latest snapshot, or an observer object whose
.next(snapshot)
method receives the latest snapshotRemarks
The observer will receive the actor’s snapshot value when it is emitted. The observer can be:
- A plain function that receives the latest snapshot, or - An observer object whose
.next(snapshot)
method receives the latest snapshotExample 1
// Observer as a plain functionconst subscription = actor.subscribe((snapshot) => {console.log(snapshot);});Example 2
// Observer as an objectconst subscription = actor.subscribe({next(snapshot) {console.log(snapshot);},error(err) {// ...},complete() {// ...}});The return value of
actor.subscribe(observer)
is a subscription object that has an.unsubscribe()
method. You can callsubscription.unsubscribe()
to unsubscribe the observer:Example 3
const subscription = actor.subscribe((snapshot) => {// ...});// Unsubscribe the observersubscription.unsubscribe();When the actor is stopped, all of its observers will automatically be unsubscribed.
method toJSON
toJSON: () => { xstate$$type: number; id: string };
class SimulatedClock
class SimulatedClock implements SimulatedClock {}
method clearTimeout
clearTimeout: (id: number) => void;
method now
now: () => number;
method setTimeout
setTimeout: (fn: (...args: any[]) => void, timeout: number) => number;
class StateMachine
class StateMachine< TContext extends MachineContext, TEvent extends EventObject, TChildren extends Record<string, AnyActorRef | undefined>, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string, TStateValue extends StateValue, TTag extends string, TInput, TOutput, TEmitted extends EventObject, TMeta extends MetaObject, TConfig extends StateSchema> implements ActorLogic< MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, TEvent, TInput, AnyActorSystem, TEmitted > {}
constructor
constructor( config: Omit< StateNodeConfig< DoNotInfer<TContext>, DoNotInfer<TEvent>, any, any, any, any, any, DoNotInfer<TOutput>, any, any >, 'output' > & { version?: string; output?: | TOutput | Mapper<TContext, DoneStateEvent<unknown>, TOutput, TEvent>; } & ( | { context?: InitialContext<LowInfer<TContext>, any, any, TEvent> } | { context: InitialContext<LowInfer<TContext>, any, any, TEvent> } ) & { schemas?: unknown }, implementations?: MachineImplementationsSimplified< TContext, TEvent, ProvidedActor, ParameterizedObject, ParameterizedObject >);
property config
config: Omit< StateNodeConfig< DoNotInfer<TContext>, DoNotInfer<TEvent>, any, any, any, any, any, DoNotInfer<TOutput>, any, any >, 'output'> & { version?: string; output?: | TOutput | Mapper<TContext, DoneStateEvent<unknown>, TOutput, TEvent>;} & ( | { context?: InitialContext<LowInfer<TContext>, any, any, TEvent> } | { context: InitialContext<LowInfer<TContext>, any, any, TEvent> } ) & { schemas?: unknown };
The raw config used to create the machine.
property definition
readonly definition: StateMachineDefinition<TContext, TEvent>;
property events
events: EventDescriptor<TEvent>[];
property id
id: string;
property implementations
implementations: MachineImplementationsSimplified< TContext, TEvent, ProvidedActor, ParameterizedObject, ParameterizedObject>;
property root
root: StateNode<TContext, TEvent>;
property schemas
schemas: {};
property states
states: StateNodesConfig<TContext, TEvent>;
property version
version?: string;
The machine's own version.
method getInitialSnapshot
getInitialSnapshot: ( actorScope: ActorScope< MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, TEvent, AnyActorSystem, TEmitted >, input?: TInput) => MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig>;
Returns the initial
State
instance, with reference toself
as anActorRef
.
method getPersistedSnapshot
getPersistedSnapshot: ( snapshot: MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, options?: unknown) => Snapshot<unknown>;
method getStateNodeById
getStateNodeById: (stateId: string) => StateNode<TContext, TEvent>;
method getTransitionData
getTransitionData: ( snapshot: MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, event: TEvent) => Array<TransitionDefinition<TContext, TEvent>>;
method microstep
microstep: ( snapshot: MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, event: TEvent, actorScope: AnyActorScope) => Array< MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >>;
Determines the next state given the current
state
andevent
. Calculates a microstep.Parameter state
The current state
Parameter event
The received event
method provide
provide: ( implementations: InternalMachineImplementations< ResolvedStateMachineTypes< TContext, DoNotInfer<TEvent>, TActor, TAction, TGuard, TDelay, TTag, TEmitted > >) => StateMachine< TContext, TEvent, TChildren, TActor, TAction, TGuard, TDelay, TStateValue, TTag, TInput, TOutput, TEmitted, TMeta, TConfig>;
Clones this state machine with the provided implementations and merges the
context
(if provided).Parameter implementations
Options (
actions
,guards
,actors
,delays
,context
) to recursively merge with the existing options.Returns
A new
StateMachine
instance with the provided implementations.
method resolveState
resolveState: ( config: { value: StateValue; context?: TContext; historyValue?: HistoryValue<TContext, TEvent>; status?: SnapshotStatus; output?: TOutput; error?: unknown; } & (Equals<TContext, MachineContext> extends false ? { context: unknown } : {})) => MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig>;
method restoreSnapshot
restoreSnapshot: ( snapshot: Snapshot<unknown>, _actorScope: ActorScope< MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, TEvent, AnyActorSystem, TEmitted >) => MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig>;
method start
start: ( snapshot: MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >) => void;
method toJSON
toJSON: () => StateMachineDefinition<TContext, TEvent>;
method transition
transition: ( snapshot: MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, event: TEvent, actorScope: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>) => MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig>;
Determines the next snapshot given the current
snapshot
and receivedevent
. Calculates a full macrostep from all microsteps.Parameter snapshot
The current snapshot
Parameter event
The received event
class StateNode
class StateNode< TContext extends MachineContext = MachineContext, TEvent extends EventObject = EventObject> {}
constructor
constructor( config: StateNodeConfig< TContext, TEvent, any, any, any, any, any, any, any, any >, options: StateNodeOptions<TContext, TEvent>);
property after
readonly after: DelayedTransitionDefinition<TContext, TEvent>[];
property always
always?: TransitionDefinition<TContext, TEvent>[];
property config
config: StateNodeConfig< TContext, TEvent, any, any, any, any, any, any, any, any>;
The raw config used to create the machine.
property definition
readonly definition: StateNodeDefinition<TContext, TEvent>;
The well-structured state node definition.
property description
description?: string;
property entry
entry: UnknownAction[];
The action(s) to be executed upon entering the state node.
property events
readonly events: EventDescriptor<TEvent>[];
All the event types accepted by this state node and its descendants.
property exit
exit: UnknownAction[];
The action(s) to be executed upon exiting the state node.
property history
history: false | 'shallow' | 'deep';
The type of history on this state node. Can be:
-
'shallow'
- recalls only top-level historical state value -'deep'
- recalls historical state value at all levels
property id
id: string;
The unique ID of the state node.
property initial
readonly initial: InitialTransitionDefinition<TContext, TEvent>;
property invoke
readonly invoke: InvokeDefinition< TContext, TEvent, ProvidedActor, ParameterizedObject, ParameterizedObject, string, any, any>[];
The logic invoked as actors by this state node.
property key
key: string;
The relative key of the state node, which represents its location in the overall state value.
property machine
machine: StateMachine< TContext, TEvent, any, any, any, any, any, any, any, any, any, any, any, any>;
The root machine node.
property meta
meta?: any;
The meta data associated with this state node, which will be returned in State instances.
property on
readonly on: TransitionDefinitionMap<TContext, TEvent>;
The mapping of events to transitions.
property order
order: number;
The order this state node appears. Corresponds to the implicit document order.
property output
output?: {} | Mapper<MachineContext, EventObject, unknown, EventObject>;
The output data sent with the "xstate.done.state._id_" event if this is a final state node.
property ownEvents
readonly ownEvents: EventDescriptor<TEvent>[];
All the events that have transitions directly from this state node.
Excludes any inert events.
property parent
parent?: StateNode<TContext, TEvent>;
The parent state node.
property path
path: string[];
The string path from the root machine node to this node.
property states
states: StateNodesConfig<TContext, TEvent>;
The child state nodes.
property tags
tags: string[];
property transitions
transitions: Map<string, TransitionDefinition<TContext, TEvent>[]>;
property type
type: 'history' | 'atomic' | 'compound' | 'parallel' | 'final';
The type of this state node:
-
'atomic'
- no child state nodes -'compound'
- nested child state nodes (XOR) -'parallel'
- orthogonal nested child state nodes (AND) -'history'
- history state node -'final'
- final state node
Interfaces
interface ActionArgs
interface ActionArgs< TContext extends MachineContext, TExpressionEvent extends EventObject, TEvent extends EventObject> extends UnifiedArg<TContext, TExpressionEvent, TEvent> {}
interface ActorLike
interface ActorLike<TCurrent, TEvent extends EventObject> extends Subscribable<TCurrent> {}
property send
send: (event: TEvent) => void;
interface ActorLogic
interface ActorLogic< in out TSnapshot extends Snapshot<unknown>, // it's invariant because it's also part of `ActorScope["self"]["getSnapshot"]` in out TEvent extends EventObject, // it's invariant because it's also part of `ActorScope["self"]["send"]` in TInput = NonReducibleUnknown, TSystem extends AnyActorSystem = AnyActorSystem, in out TEmitted extends EventObject = EventObject> {}
Represents logic which can be used by an actor.
TSnapshot - The type of the snapshot. TEvent - The type of the event object. TInput - The type of the input. TSystem - The type of the actor system.
property config
config?: unknown;
The initial setup/configuration used to create the actor logic.
property getInitialSnapshot
getInitialSnapshot: ( actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>, input: TInput) => TSnapshot;
Called to provide the initial state of the actor.
Parameter actorScope
The actor scope.
Parameter input
The input for the initial state.
Returns
The initial state.
property getPersistedSnapshot
getPersistedSnapshot: ( snapshot: TSnapshot, options?: unknown) => Snapshot<unknown>;
Obtains the internal state of the actor in a representation which can be be persisted. The persisted state can be restored by
restoreSnapshot
.Parameter snapshot
The current state.
Returns
The a representation of the internal state to be persisted.
property restoreSnapshot
restoreSnapshot?: ( persistedState: Snapshot<unknown>, actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>) => TSnapshot;
Called when Actor is created to restore the internal state of the actor given a persisted state. The persisted state can be created by
getPersistedSnapshot
.Parameter persistedState
The persisted state to restore from.
Parameter actorScope
The actor scope.
Returns
The restored state.
property start
start?: ( snapshot: TSnapshot, actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>) => void;
Called when the actor is started.
Parameter snapshot
The starting state.
Parameter actorScope
The actor scope.
property transition
transition: ( snapshot: TSnapshot, message: TEvent, actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>) => TSnapshot;
Transition function that processes the current state and an incoming message to produce a new state.
Parameter snapshot
The current state.
Parameter message
The incoming message.
Parameter actorScope
The actor scope.
Returns
The new state.
interface ActorOptions
interface ActorOptions<TLogic extends AnyActorLogic> {}
property clock
clock?: Clock;
The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
Remarks
You can create your own “clock”. The clock interface is an object with two functions/methods:
-
setTimeout
- same arguments aswindow.setTimeout(fn, timeout)
-clearTimeout
- same arguments aswindow.clearTimeout(id)
By default, the native
setTimeout
andclearTimeout
functions are used.For testing, XState provides
SimulatedClock
.See Also
property devTools
devTools?: never;
Deprecated
Use
inspect
instead.
property id
id?: string;
The custom
id
for referencing this service.
property input
input?: InputFrom<TLogic>;
The input data to pass to the actor.
property inspect
inspect?: | Observer<InspectionEvent> | ((inspectionEvent: InspectionEvent) => void);
A callback function or observer object which can be used to inspect actor system updates.
Remarks
If a callback function is provided, it can accept an inspection event argument. The types of inspection events that can be observed include:
-
@xstate.actor
- An actor ref has been created in the system -@xstate.event
- An event was sent from a source actor ref to a target actor ref in the system -@xstate.snapshot
- An actor ref emitted a snapshot due to a received eventExample 1
import { createMachine } from 'xstate';const machine = createMachine({// ...});const actor = createActor(machine, {inspect: (inspectionEvent) => {if (inspectionEvent.actorRef === actor) {// This event is for the root actor}if (inspectionEvent.type === '@xstate.actor') {console.log(inspectionEvent.actorRef);}if (inspectionEvent.type === '@xstate.event') {console.log(inspectionEvent.sourceRef);console.log(inspectionEvent.actorRef);console.log(inspectionEvent.event);}if (inspectionEvent.type === '@xstate.snapshot') {console.log(inspectionEvent.actorRef);console.log(inspectionEvent.event);console.log(inspectionEvent.snapshot);}}});Alternately, an observer object (
{ next?, error?, complete? }
) can be provided:Example 2
const actor = createActor(machine, {inspect: {next: (inspectionEvent) => {if (inspectionEvent.actorRef === actor) {// This event is for the root actor}if (inspectionEvent.type === '@xstate.actor') {console.log(inspectionEvent.actorRef);}if (inspectionEvent.type === '@xstate.event') {console.log(inspectionEvent.sourceRef);console.log(inspectionEvent.actorRef);console.log(inspectionEvent.event);}if (inspectionEvent.type === '@xstate.snapshot') {console.log(inspectionEvent.actorRef);console.log(inspectionEvent.event);console.log(inspectionEvent.snapshot);}}}});
property logger
logger?: (...args: any[]) => void;
Specifies the logger to be used for
log(...)
actions. Defaults to the nativeconsole.log(...)
method.
property parent
parent?: AnyActorRef;
property snapshot
snapshot?: Snapshot<unknown>;
Initializes actor logic from a specific persisted internal state.
Remarks
If the state is compatible with the actor logic, when the actor is started it will be at that persisted state. Actions from machine actors will not be re-executed, because they are assumed to have been already executed. However, invocations will be restarted, and spawned actors will be restored recursively.
Can be generated with Actor.getPersistedSnapshot.
See Also
https://stately.ai/docs/persistence
property src
src?: string | AnyActorLogic;
The source actor logic.
property state
state?: Snapshot<unknown>;
Deprecated
Use
snapshot
instead.
property systemId
systemId?: string;
The system ID to register this actor under.
interface ActorRef
interface ActorRef< TSnapshot extends Snapshot<unknown>, TEvent extends EventObject, TEmitted extends EventObject = EventObject> extends Subscribable<TSnapshot>, InteropObservable<TSnapshot> {}
property getPersistedSnapshot
getPersistedSnapshot: () => Snapshot<unknown>;
property getSnapshot
getSnapshot: () => TSnapshot;
property id
id: string;
The unique identifier for this actor relative to its parent.
property on
on: <TType extends TEmitted['type'] | '*'>( type: TType, handler: ( emitted: TEmitted & (TType extends '*' ? {} : { type: TType; }) ) => void) => Subscription;
property send
send: (event: TEvent) => void;
property sessionId
sessionId: string;
property src
src: string | AnyActorLogic;
property start
start: () => void;
property stop
stop: () => void;
property system
system: AnyActorSystem;
property toJSON
toJSON?: () => any;
interface ActorScope
interface ActorScope< TSnapshot extends Snapshot<unknown>, TEvent extends EventObject, TSystem extends AnyActorSystem = AnyActorSystem, TEmitted extends EventObject = EventObject> {}
property defer
defer: (fn: () => void) => void;
property emit
emit: (event: TEmitted) => void;
property id
id: string;
property logger
logger: (...args: any[]) => void;
property self
self: ActorRef<TSnapshot, TEvent, TEmitted>;
property sessionId
sessionId: string;
property stopChild
stopChild: (child: AnyActorRef) => void;
property system
system: TSystem;
interface ActorSystem
interface ActorSystem<T extends ActorSystemInfo> {}
property get
get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;
property getSnapshot
getSnapshot: () => { _scheduledEvents: Record<string, ScheduledEvent>;};
property inspect
inspect: ( observer: | Observer<InspectionEvent> | ((inspectionEvent: InspectionEvent) => void)) => Subscription;
property scheduler
scheduler: Scheduler;
property start
start: () => void;
interface ActorSystemInfo
interface ActorSystemInfo {}
property actors
actors: Record<string, AnyActorRef>;
interface AnyEventObject
interface AnyEventObject extends EventObject {}
index signature
[key: string]: any;
interface AssignAction
interface AssignAction< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TActor extends ProvidedActor> {}
call signature
(args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
interface AssignArgs
interface AssignArgs< TContext extends MachineContext, TExpressionEvent extends EventObject, TEvent extends EventObject, TActor extends ProvidedActor> extends ActionArgs<TContext, TExpressionEvent, TEvent> {}
property spawn
spawn: Spawner<TActor>;
interface AtomicStateNodeConfig
interface AtomicStateNodeConfig< TContext extends MachineContext, TEvent extends EventObject> extends StateNodeConfig< TContext, TEvent, TODO, TODO, TODO, TODO, TODO, TODO, TODO, // emitted TODO > {}
interface BaseActorRef
interface BaseActorRef<TEvent extends EventObject> {}
property send
send: (event: TEvent) => void;
interface CancelAction
interface CancelAction< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject> {}
call signature
(args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
interface DelayedTransitionDefinition
interface DelayedTransitionDefinition< TContext extends MachineContext, TEvent extends EventObject> extends TransitionDefinition<TContext, TEvent> {}
property delay
delay: number | string | DelayExpr<TContext, TEvent, undefined, TEvent>;
interface DoneActorEvent
interface DoneActorEvent<TOutput = unknown, TId extends string = string> extends EventObject {}
interface DoneStateEvent
interface DoneStateEvent<TOutput = unknown> extends EventObject {}
interface EmitAction
interface EmitAction< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TEmitted extends EventObject> {}
call signature
(args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
interface EnqueueActionsAction
interface EnqueueActionsAction< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string> {}
call signature
(args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
interface ErrorActorEvent
interface ErrorActorEvent<TErrorData = unknown, TId extends string = string> extends EventObject {}
interface HistoryStateNode
interface HistoryStateNode<TContext extends MachineContext> extends StateNode<TContext> {}
interface HistoryStateNodeConfig
interface HistoryStateNodeConfig< TContext extends MachineContext, TEvent extends EventObject> extends AtomicStateNodeConfig<TContext, TEvent> {}
interface InitialTransitionConfig
interface InitialTransitionConfig< TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string> extends TransitionConfig< TContext, TEvent, TEvent, TActor, TAction, TGuard, TDelay, TODO, // TEmitted TODO > {}
property target
target: string;
interface InitialTransitionDefinition
interface InitialTransitionDefinition< TContext extends MachineContext, TEvent extends EventObject> extends TransitionDefinition<TContext, TEvent> {}
interface InspectedActorEvent
interface InspectedActorEvent extends BaseInspectionEventProperties {}
property type
type: '@xstate.actor';
interface InspectedEventEvent
interface InspectedEventEvent extends BaseInspectionEventProperties {}
interface InspectedSnapshotEvent
interface InspectedSnapshotEvent extends BaseInspectionEventProperties {}
interface InteropObservable
interface InteropObservable<T> {}
property [Symbol.observable]
[Symbol.observable]: () => InteropSubscribable<T>;
interface InteropSubscribable
interface InteropSubscribable<T> {}
method subscribe
subscribe: (observer: Observer<T>) => Subscription;
interface InvokeDefinition
interface InvokeDefinition< TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string, TEmitted extends EventObject, TMeta extends MetaObject> {}
property id
id: string;
property input
input?: | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent> | NonReducibleUnknown;
property onDone
onDone?: | string | SingleOrArray< TransitionConfig< TContext, DoneActorEvent<unknown>, TEvent, TActor, TAction, TGuard, TDelay, TEmitted, TMeta > >;
The transition to take upon the invoked child machine reaching its final top-level state.
property onError
onError?: | string | SingleOrArray< TransitionConfig< TContext, ErrorActorEvent, TEvent, TActor, TAction, TGuard, TDelay, TEmitted, TMeta > >;
The transition to take upon the invoked child machine sending an error event.
property onSnapshot
onSnapshot?: | string | SingleOrArray< TransitionConfig< TContext, SnapshotEvent, TEvent, TActor, TAction, TGuard, TDelay, TEmitted, TMeta > >;
property src
src: AnyActorLogic | string;
The source of the actor logic to be invoked
property systemId
systemId: string | undefined;
property toJSON
toJSON: () => Omit< InvokeDefinition< TContext, TEvent, TActor, TAction, TGuard, TDelay, TEmitted, TMeta >, 'onDone' | 'onError' | 'toJSON'>;
interface LogAction
interface LogAction< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject> {}
call signature
(args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
interface MachineImplementationsSimplified
interface MachineImplementationsSimplified< TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor = ProvidedActor, TAction extends ParameterizedObject = ParameterizedObject, TGuard extends ParameterizedObject = ParameterizedObject> {}
property actions
actions: ActionFunctionMap<TContext, TEvent, TActor, TAction>;
property actors
actors: Record< string, | AnyActorLogic | { src: AnyActorLogic; input: Mapper<TContext, TEvent, unknown, TEvent> | NonReducibleUnknown; }>;
property delays
delays: DelayFunctionMap<TContext, TEvent, TAction>;
property guards
guards: GuardMap<TContext, TEvent, TGuard>;
interface MachineTypes
interface MachineTypes< TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string, TTag extends string, TInput, TOutput, TEmitted extends EventObject, TMeta extends MetaObject> extends SetupTypes< TContext, TEvent, never, TTag, TInput, TOutput, TEmitted, TMeta > {}
interface ParameterizedObject
interface ParameterizedObject {}
interface ProvidedActor
interface ProvidedActor {}
interface RaiseAction
interface RaiseAction< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TDelay extends string> {}
call signature
(args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
interface RaiseActionOptions
interface RaiseActionOptions< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TDelay extends string> {}
interface RaiseActionParams
interface RaiseActionParams< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TDelay extends string> extends RaiseActionOptions<TContext, TExpressionEvent, TParams, TEvent, TDelay> {}
property event
event: TEvent | SendExpr<TContext, TExpressionEvent, TParams, TEvent, TEvent>;
interface ResolvedStateMachineTypes
interface ResolvedStateMachineTypes< TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string, TTag extends string, TEmitted extends EventObject = EventObject> {}
Deprecated
interface SendToAction
interface SendToAction< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TDelay extends string> {}
call signature
(args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
interface SendToActionOptions
interface SendToActionOptions< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TDelay extends string> extends RaiseActionOptions<TContext, TExpressionEvent, TParams, TEvent, TDelay> {}
interface SendToActionParams
interface SendToActionParams< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TSentEvent extends EventObject, TEvent extends EventObject, TDelay extends string> extends SendToActionOptions<TContext, TExpressionEvent, TParams, TEvent, TDelay> {}
property event
event: | TSentEvent | SendExpr<TContext, TExpressionEvent, TParams, TSentEvent, TEvent>;
interface SetupTypes
interface SetupTypes< TContext extends MachineContext, TEvent extends EventObject, TChildrenMap extends Record<string, string>, TTag extends string, TInput, TOutput, TEmitted extends EventObject, TMeta extends MetaObject> {}
interface SimulatedClock
interface SimulatedClock extends Clock {}
interface SnapshotEvent
interface SnapshotEvent<TSnapshot extends Snapshot<unknown> = Snapshot<unknown>> extends EventObject {}
interface SpawnAction
interface SpawnAction< TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TActor extends ProvidedActor> {}
call signature
(args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
interface StateConfig
interface StateConfig<TContext extends MachineContext, TEvent extends EventObject> {}
property children
children: Record<string, AnyActorRef>;
property context
context: TContext;
property error
error?: unknown;
property historyValue
historyValue?: HistoryValue<TContext, TEvent>;
property machine
machine?: StateMachine< TContext, TEvent, any, any, any, any, any, any, any, any, any, any, any, // TMeta any>;
property output
output?: any;
property status
status: SnapshotStatus;
interface StateLike
interface StateLike<TContext extends MachineContext> {}
interface StateMachineDefinition
interface StateMachineDefinition< TContext extends MachineContext, TEvent extends EventObject> extends StateNodeDefinition<TContext, TEvent> {}
interface StateMachineTypes
interface StateMachineTypes {}
interface StateNodeConfig
interface StateNodeConfig< TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string, TTag extends string, TOutput, TEmitted extends EventObject, TMeta extends MetaObject> {}
property after
after?: DelayedTransitions<TContext, TEvent, TActor, TAction, TGuard, TDelay>;
The mapping (or array) of delays (in milliseconds) to their potential transition(s). The delayed transitions are taken after the specified delay in an interpreter.
property always
always?: TransitionConfigOrTarget< TContext, TEvent, TEvent, TActor, TAction, TGuard, TDelay, TEmitted, TMeta>;
An eventless transition that is always taken when this state node is active.
property description
description?: string;
A text description of the state node
property entry
entry?: Actions< TContext, TEvent, TEvent, undefined, TActor, TAction, TGuard, TDelay, TEmitted>;
The action(s) to be executed upon entering the state node.
property exit
exit?: Actions< TContext, TEvent, TEvent, undefined, TActor, TAction, TGuard, TDelay, TEmitted>;
The action(s) to be executed upon exiting the state node.
property history
history?: 'shallow' | 'deep' | boolean | undefined;
Indicates whether the state node is a history state node, and what type of history: shallow, deep, true (shallow), false (none), undefined (none)
property id
id?: string | undefined;
The unique ID of the state node, which can be referenced as a transition target via the
#id
syntax.
property initial
initial?: | InitialTransitionConfig<TContext, TEvent, TActor, TAction, TGuard, TDelay> | string | undefined;
The initial state transition.
property invoke
invoke?: SingleOrArray< InvokeConfig< TContext, TEvent, TActor, TAction, TGuard, TDelay, TEmitted, TMeta >>;
The services to invoke upon entering this state node. These services will be stopped upon exiting this state node.
property meta
meta?: TMeta;
The meta data associated with this state node, which will be returned in State instances.
property on
on?: TransitionsConfig< TContext, TEvent, TActor, TAction, TGuard, TDelay, TEmitted, TMeta>;
The mapping of event types to their potential transition(s).
property onDone
onDone?: | string | SingleOrArray< TransitionConfig< TContext, DoneStateEvent, TEvent, TActor, TAction, TGuard, TDelay, TEmitted, TMeta > > | undefined;
The potential transition(s) to be taken upon reaching a final child state node.
This is equivalent to defining a
[done(id)]
transition on this state node'son
property.
property order
order?: number;
The order this state node appears. Corresponds to the implicit document order.
property output
output?: Mapper<TContext, TEvent, unknown, TEvent> | NonReducibleUnknown;
The output data sent with the "xstate.done.state._id_" event if this is a final state node.
The output data will be evaluated with the current
context
and placed on the.data
property of the event.
property parent
parent?: StateNode<TContext, TEvent>;
property states
states?: | StatesConfig< TContext, TEvent, TActor, TAction, TGuard, TDelay, TTag, NonReducibleUnknown, TEmitted, TMeta > | undefined;
The mapping of state node keys to their state node configurations (recursive).
property tags
tags?: SingleOrArray<TTag>;
The tags for this state node, which are accumulated into the
state.tags
property.
property target
target?: string;
A default target for a history state
property type
type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';
The type of this state node:
-
'atomic'
- no child state nodes -'compound'
- nested child state nodes (XOR) -'parallel'
- orthogonal nested child state nodes (AND) -'history'
- history state node -'final'
- final state node
interface StateNodeDefinition
interface StateNodeDefinition< TContext extends MachineContext, TEvent extends EventObject> {}
property description
description?: string;
property entry
entry: UnknownAction[];
property exit
exit: UnknownAction[];
property history
history: boolean | 'shallow' | 'deep' | undefined;
property id
id: string;
property initial
initial: InitialTransitionDefinition<TContext, TEvent> | undefined;
property invoke
invoke: Array< InvokeDefinition< TContext, TEvent, TODO, TODO, TODO, TODO, TODO, // TEmitted TODO >>;
property key
key: