NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm, #4208 most downloaded on npm
Finite State Machines and Statecharts for the Modern Web.
Latest stable
5.33.4
Last release 12 days ago
07 Nov 2026
Ships on a steady schedule
a new release about every 1 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
9 years old
352 releases · first in 2017
Drag across the ruler to compare, or tap a release to open it.
86b43ea: Export setup system helper types used by public machine types.
86b43ea: Export setup system helper types used by public machine types.
This avoids inferred machine types referring to internal declaration paths when
setup(...) includes a typed system registry.
54205cc: Export setup helper types for libraries that return or decorate setup-bound objects while preserving native setup(...).createMachine(...) typ
54205cc: Export setup helper types for libraries that return or decorate setup-bound objects while preserving native setup(...).createMachine(...) typing.
import {
setup,
type AnySetupConfig,
type SetupReturnFromConfig
} from 'xstate';
function decorateSetup<const TConfig extends AnySetupConfig>(
config: TConfig
): SetupReturnFromConfig<TConfig> & { extra: true } {
const s = setup(config) as SetupReturnFromConfig<TConfig>;
return Object.assign(s, { extra: true as const });
}
{ type: 'SEND' } is accepted for an empty SEND payload schema while non-empty schemas still require their payload fields.onDone callbacks now receive the invoked actor's output type, and machine.provide({ actorSources }) accepts compatible actor implementations with sound input/output variance.Your coding agent can read these notes before it upgrades. Set up the MCP server →
667d1c7: Done transitions now receive output directly in callback arguments.
667d1c7: Done transitions now receive output directly in callback arguments.
invoke: {
src: fetchUser,
onDone: ({ output }) => {
output.name;
}
}
The direct output value is only provided for XState done events, such as
xstate.done.actor.* and xstate.done.state.*.
89895f9: Add createSystem({ registry }) for declaring typed actor registry keys and creating actors in that system.
89895f9: Add createSystem({ registry }) for declaring typed actor registry keys and creating actors in that system.
Registry keys are assigned with registryKey on invokes, spawned actors, and root actors created from the system. Registry keys are checked against the declared registry when using createSystem.
const system = createSystem({
registry: {
receiver: receiverLogic
}
});
const machine = system.setup().createMachine({
invoke: {
src: receiverLogic,
registryKey: 'receiver'
}
});
const actor = system.createActor(machine).start();
system.get('receiver')?.send({ type: 'HELLO' });
89895f9: Static transition config objects may now include a shallow context patch.
createMachine({
context: { draftAnyway: false, count: 0 },
initial: 'idle',
states: {
idle: {
on: {
DRAFT_ANYWAY: {
target: 'drafting',
context: { draftAnyway: true }
}
}
},
drafting: {}
}
});
The patch is shallow-merged with the current context, just like context returned from a transition function. Setup-typed machines still require any keys needed by the target state's narrowed context.
ecd97db: State transition functions now type enq with the machine's events and emitted events.
ecd97db: State transition functions now type enq with the machine's events and emitted events.
setup({
schemas: {
events: {
go: types<{}>()
}
}
}).createMachine({
states: {
active: {
on: {
go: (_args, enq) => {
enq.raise({ type: 'go' });
}
}
}
}
});
4b5b14f: Transition functions may now return only a target when the target state's context is compatible with the current context.
setup({
schemas: {
context: types<{ count: number }>(),
events: {
next: types<{}>()
}
}
}).createMachine({
context: { count: 0 },
initial: 'idle',
states: {
idle: {
on: {
next: () => ({ target: 'done' })
}
},
done: {}
}
});
297f851: String target shorthand is no longer accepted for transition configs. Use the object form with target instead:
297f851: String target shorthand is no longer accepted for transition configs. Use the object form with target instead:
createMachine({
initial: 'idle',
states: {
idle: {
on: {
start: { target: 'active' }
}
},
active: {}
}
});
@public or @experimental stability tags.c3f7a9d: Actor logic now returns effects from both regular and initial transitions.
c3f7a9d: Actor logic now returns effects from both regular and initial transitions.
Hand-written actor logic should return [snapshot, effects] from transition(...) and provide initialTransition(...) for creating the initial [snapshot, effects] tuple. getInitialSnapshot(...) remains available for snapshot-only reads.
const logic = {
transition: (snapshot, event) => [snapshot, []],
initialTransition: (input, _scope) => [
{
status: 'active',
output: undefined,
error: undefined,
input
},
[]
],
getInitialSnapshot: (scope, input) =>
logic.initialTransition(input, scope)[0]
};
transition(...) and initialTransition(...) continue to return [snapshot, actions] for machine logic.
fromStore(...) effects now run after the actor snapshot is committed, so effect callbacks read the updated snapshot from enqueue.getSnapshot().
309b106: Add schemas.children for explicitly typing child actor refs by child ID. Declared child refs type children.someId, child snapshots, and invoke configs so invoke: { id: 'someId', src } must match the declared child actor contract.
fa2bbf0: Built-in executable effects returned from transition(...) and initialTransition(...) are now easier to inspect declaratively.
Use isBuiltInExecutableAction(effect) to narrow an executable effect to XState's built-in effect union, then switch on effect.type to access stable, named metadata fields:
const [snapshot, effects] = initialTransition(machine);
for (const effect of effects) {
if (!isBuiltInExecutableAction(effect)) {
continue;
}
switch (effect.type) {
case '@xstate.start':
effect.id;
effect.logic;
effect.src;
effect.input;
break;
case '@xstate.sendTo':
effect.target;
effect.event;
effect.delay;
break;
case '@xstate.raise':
effect.event;
effect.delay;
break;
}
}
The built-in stop effect is now exposed as @xstate.stop, matching @xstate.start.
5b6df81: xstate is now a required peer dependency of @xstate/react, @xstate/vue, @xstate/svelte, and @xstate/solid. Package managers now warn when xstate is missing instead of letting the adapter fail at runtime.
useActorRef(), useActor(), and useMachine() in @xstate/react no longer write implementations provided on a later render onto the machine passed on the first render. A module-level machine shared by several components keeps its own implementations:
const machine = createMachine({
actions: { notify: () => {} },
on: { DO: ({ actions }, enq) => enq(actions.notify) }
});
function Custom({ onNotify }) {
// Only this component's actor uses `onNotify`.
useActorRef(machine.provide({ actions: { notify: onNotify } }));
return null;
}
function Plain() {
// Still uses the original `notify`.
useActorRef(machine);
return null;
}
```ts const machine = createMachine({ schemas: { context: z.object({ count: z.number() }), events: { inc: z.object({ by: z.number() }) } }, context: {
#44 0a883ad Thanks @pull! - Expose machine.schemas as a public runtime-readable schema contract.
const machine = createMachine({
schemas: {
context: z.object({ count: z.number() }),
events: {
inc: z.object({ by: z.number() })
}
},
context: { count: 0 }
});
machine.schemas?.events?.inc;
#44 d95287b Thanks @pull! - Serialize function implementations as portable code expressions.
Functions in guards, actions, delays, and inline machine config now serialize as:
{ '@type': 'code', lang: 'ts', expr: '() => true' }
Values that cannot be represented as code or JSON still serialize with explicit $unserializable markers.
useActor, useActorRef and useMachine now require input for machines that declare a required input schema, matching createActor. Passing a persisted snapshot instead of input is allowed.useActor, useActorRef and useMachine now require input for machines that declare a required input schema, matching createActor. Passing a persisted snapshot instead of input is allowed.@xstate/svelte as an ES module so import resolves to real ESM instead of a CommonJS wrapper. This fixes Vitest and other ESM tooling failing with require('svelte/store') errors against Svelte's ESM-only builds. require('@xstate/svelte') still works on Node versions that support require(esm).`ts const machine = createMachine({ context: { value: 0 }, initial: 'idle', states: { idle: { on: { start: () => ({ target: 'active', context: { value
#44 d6a537e Thanks @pull! - Fixed a bug where an invoked actor's input (and a dynamic src function) received the context from before the transition that entered the invoking state, rather than the updated context. Now, when a transition updates context and targets a state that invokes an actor, the actor's input sees the updated context — consistent with that state's entry actions.
const machine = createMachine({
context: { value: 0 },
initial: 'idle',
states: {
idle: {
on: {
start: () => ({ target: 'active', context: { value: 100 } })
}
},
active: {
invoke: {
src: asyncLogic,
// now receives { value: 100 } instead of { value: 0 }
input: ({ context }) => ({ val: context.value })
}
}
}
});
69b6663: Keep selected values current when subscriptions start or resume. Vue and Solid now expose terminal error snapshots, and Solid preserves array/object context changes without changing the actor's source data. Vue uses one snapshot subscription per useActor call.
React store selectors now honor custom comparisons when the selector argument is omitted.
The user-visible consequence: a child that fails synchronously while starting now surfaces that failure through the invoking state's onError transitio
#44 52970ea Thanks @pull! - Invoked and spawned actors are no longer started directly by actor.start(). They now start as part of the transition that creates them (via an internal deferred start action), the same way other entry effects run.
The user-visible consequence: a child that fails synchronously while starting now surfaces that failure through the invoking state's onError transition instead of throwing out of actor.start():
const machine = createMachine({
initial: 'loading',
states: {
loading: {
invoke: {
src: createAsyncLogic({
run: () => {
throw new Error('boom'); // sync failure on start
}
}),
onError: 'failed'
}
},
failed: {}
}
});
const actor = createActor(machine).start(); // does not throw
actor.getSnapshot().value; // 'failed'
Restored (rehydrated) children that were active when a snapshot was persisted are still restarted on actor.start(), so persistence behavior is unchanged.
#44 52970ea Thanks @pull! - Actions, guards, and transitions are now plain inline functions, and the v5 action/guard creators are removed.
Removed exports: assign, raise, sendTo, sendParent, forwardTo, emit, log, cancel, spawnChild, stop, stopChild, enqueueActions, and the guard creators and, or, not, stateIn.
Instead, a transition/action/guard is a function (args, enq) => ...:
{ context } patch (no more assign).enq enqueue object: enq.raise, enq.sendTo, enq.emit, enq.log, enq.cancel, enq.spawn, enq.stop, plus enq(fn, ...args) for arbitrary effects.undefined/false to block).- import { assign, raise, sendTo, and, not } from 'xstate';
const machine = createMachine({
context: { count: 0 },
on: {
- INC: {
- guard: and([not('isMax'), 'isReady']),
- actions: assign({ count: ({ context }) => context.count + 1 })
- }
+ INC: ({ context, guards }) => {
+ if (guards.isMax(context) || !guards.isReady(context)) return;
+ return { context: { count: context.count + 1 } };
+ }
}
});
The stateIn guard is replaced by checking the snapshot directly — use snapshot.matches(...) inside a transition function:
on: {
CHECK: ({ self }) => {
if (self.getSnapshot().matches({ b: 'b2' })) {
return { target: 'a2' };
}
};
}
For matching by state id (the '#id' form, which matches() doesn't resolve), the exported checkStateIn(snapshot, '#id') helper is also available.
#44 52970ea Thanks @pull! - Remove the deprecated interpret function and Interpreter type. Use createActor(...) and Actor (or ActorRefFrom<...>) instead.
- import { interpret, type Interpreter } from 'xstate';
- const actor = interpret(machine);
+ import { createActor, type Actor } from 'xstate';
+ const actor = createActor(machine);
#44 52970ea Thanks @pull! - schemas is now the way to type a machine, replacing v5's types: {} as {...}. Each schemas field accepts any Standard Schema (Zod, Valibot, …) for both type inference and (where supported) runtime validation, or types<T>() for types only.
Notably, schemas.events is a map of event-type → payload schema, inferred into a discriminated union keyed by type:
import { createMachine } from 'xstate';
import { z } from 'zod';
const machine = createMachine({
schemas: {
context: z.object({ count: z.number() }),
events: {
inc: z.object({ by: z.number() }),
reset: z.object({})
},
input: z.object({ start: z.number() }),
output: z.object({ total: z.number() }),
emitted: { changed: z.object({ count: z.number() }) },
tags: z.union([z.literal('busy'), z.literal('idle')]),
meta: z.object({ label: z.string() })
},
context: ({ input }) => ({ count: input.start }),
initial: 'active',
states: {
active: {
on: {
inc: ({ context, event }) => ({
context: { count: context.count + event.by }
})
}
}
}
});
context → context type (literal initial values are widened, so updates typecheck).events → { type: 'inc'; by: number } | { type: 'reset' }; payloads are typed on event in every transition/action/guard function.input → typed createActor(machine, { input }) and the context initializer argument.output → typed snapshot.output.emitted → typed actor.on('changed', (ev) => ev.count).tags → constrains snapshot.hasTag(...).meta → typed state meta.actors, actions, guards, and delays are top-level config keys (now inline functions), not schemas keys.
#44 96aee67 Thanks @pull! - Separate concrete actors from actor refs in public types. ActorRef now represents the consumer-facing contract for sending events, reading published snapshots, and listening to emitted events with actorRef.on(...); concrete Actor instances provide lifecycle and runtime capabilities and still satisfy actor ref contracts.
#44 52970ea Thanks @pull! - setup(...) no longer registers implementations. It now takes only { schemas?, states? } and returns { createMachine, createStateConfig, states }.
In v5, setup({ schemas, actors, actions, guards, delays }) registered named implementations and returned action creators (assign, sendTo, raise, …). In v6, actions/guards/actors/delays are plain inline functions, so setup no longer accepts or returns them. Its job is now machine- and state-level typing: it validates state keys, initial, and transition targets against the declared states, and types per-state input/context.
const { createMachine, createStateConfig } = setup({
schemas: {
context: types<{ count: number }>(),
events: { INC: types<{ value: number }>() }
},
states: {
idle: {},
loading: { schemas: { input: z.object({ userId: z.string() }) } }
}
});
setup().createMachine() merges setup schemas with config schemas. Bare createMachine({ schemas }) infers the same machine-level types without the state-key checks.
#44 52970ea Thanks @pull! - Add actor.trigger — a typed event-sender proxy. actor.trigger.EVENT(payload) is shorthand for actor.send({ type: 'EVENT', ...payload }):
actor.trigger.NEXT();
actor.trigger.INC({ by: 5 });
#44 021cc56 Thanks @pull! - Machine JSON revival now preserves more of the serialized machine definition, including delayed transitions, state timeouts, state tags, state output, invoke input, invoke completion transitions, invoke timeouts, and implementation maps passed to createMachineFromConfig.
const machine = createMachineFromConfig(
{
initial: 'loading',
states: {
loading: {
invoke: {
src: 'loadUser',
input: { userId: '42' },
onDone: { target: 'done' },
timeout: 5000,
onTimeout: { target: 'timedOut' }
}
},
done: {},
timedOut: {}
}
},
{
actors: { loadUser }
}
);
The migration codemod now reports manual review notes for known non-rename migrations such as fromPromise(...), return assign(...), object-form actions/guards, and legacy types: {} schema declarations.
#44 52970ea Thanks @pull! - createLogic and createAsyncLogic gain a durable-effect enqueue API on their run function's second argument (enq).
enq.effect(key?, fn) registers a side effect that runs once per key (an unnamed effect runs every transition) and is cleaned up when the actor stops.enq.step(key, asyncFn) (async logic) is an await-able step whose result is memoized into the persisted snapshot under snapshot.effects[key]. A rehydrated actor replays run but skips steps that already completed, so long-running async logic is resumable across persistence.const logic = createAsyncLogic({
run: async (_, enq) => {
const user = await enq.step('fetchUser', () => fetchUser());
const order = await enq.step('createOrder', () => createOrder(user.id));
return order.id;
}
});
// snapshot.effects.fetchUser === { status: 'done', output: { id: 1 } }
A pending step can also be resolved externally by sending { type: 'xstate.logic.effect.resolve', key, output }. The LogicEnqueue, LogicEffect, and LogicEffectState types are exported.
#44 52970ea Thanks @pull! - Add timeouts and duration-string delays.
State-level timeout / onTimeout — declare a timeout on a state that transitions when the duration elapses (and is cancelled if the state is exited first):
states: {
waiting: {
timeout: 1000,
onTimeout: 'escalated'
},
escalated: {}
}
createAsyncLogic timeout — async logic can time out; when it does, the run's AbortSignal is aborted and the actor errors with a TimeoutError (exported from xstate):
const logic = createAsyncLogic({
timeout: '10ms',
run: ({ signal }) => fetch('/slow', { signal })
});
Invoke-level timeout / onTimeout — an invocation can race a timeout: if the invoked actor doesn't complete in time, the onTimeout transition is taken; if it settles first (or the state is exited), the timeout is cancelled. timeout accepts a number, a duration string, a referenced delay, or a function ({ context, event }) => duration. Both state- and invoke-level timeout throw at construction if declared without a matching onTimeout.
working: {
invoke: {
src: fetchReport,
timeout: ({ context }) => context.slaMs,
onTimeout: 'timedOut',
onDone: 'done'
}
}
Duration-string delays — delays (including after and timeout) accept human-readable strings like '10ms' and '5s', as well as ISO-8601 durations like 'PT2M', in addition to numbers:
waiting: {
after: {
'5s': 'timedOut'
}
}
#44 d9079cd Thanks @pull! - Logic creators now accept Standard Schemas for type inference.
createLogic(...) and createAsyncLogic(...) accept schemas.input and
schemas.output:
const loadUser = createAsyncLogic({
schemas: {
input: z.object({ userId: z.string() }),
output: z.object({ name: z.string() })
},
run: async ({ input }) => {
input.userId; // string
return {
name: 'David'
};
}
});
The schemas are type-only for now. Runtime validation will be added later as an opt-in behavior.
createCallbackLogic(...), createObservableLogic(...), and createEventObservableLogic(...) also accept schemas.input with object-form config:
const logic = createCallbackLogic({
schemas: {
input: z.object({ userId: z.string() })
},
run: ({ input }) => {
input.userId; // string
}
});
#44 52970ea Thanks @pull! - Add createStateConfig(...) — author a standalone, fully-typed state node config (with schemas) that can be composed into a machine, mirroring how setup(...).createMachine(...) infers types.
import { createStateConfig } from 'xstate';
const loading = createStateConfig({
on: {
RESOLVE: 'success'
}
});
This is the building block for authoring machines as plain data: a createStateConfig node is a typed, serializable config object you compose into a machine — useful for data-first / JSON-driven state machines (round-tripping with serializeMachine/createMachineFromConfig) while keeping per-state schema typing.
#44 52970ea Thanks @pull! - Add enq.listen and enq.subscribeTo for subscribing to other actors from inside transition/action functions.
enq.listen(ref, eventType, mapper) subscribes to events emitted by another actor (supports wildcards like 'data.*') and relays a mapped event back to the current actor.enq.subscribeTo(ref, mappers) subscribes to another actor's snapshot/done/error (pass { snapshot, done, error }, or a single function as snapshot shorthand). It also accepts an atom, in which case the mapper receives the atom's current value.Both return a stoppable child ref (enq.stop(ref)) and are torn down automatically when the parent stops. The underlying logic creators createListenerLogic and createSubscriptionLogic are exported.
entry: (_, enq) => {
const child = enq.spawn(childLogic, { id: 'child' });
enq.listen(child, 'data.*', (ev) => ({ type: 'DATA', value: ev.value }));
enq.subscribeTo(child, {
done: (output) => ({ type: 'CHILD_DONE', output })
});
};
#44 52970ea Thanks @pull! - Add internalEvents: a list of event types that may be raised from within the machine (e.g. via enq.raise(...)) but are rejected when sent to the actor from the outside.
const machine = createMachine({
internalEvents: ['tick'] as const,
initial: 'idle',
states: {
idle: {
on: {
start: (_, enq) => {
enq.raise({ type: 'tick' }); // allowed internally
},
tick: 'running'
}
},
running: {}
}
});
// actor.send({ type: 'tick' }) from outside is rejected
#44 021cc56 Thanks @pull! - State-level schemas.context now narrows context types for state actions, transition functions, and snapshots checked with snapshot.matches(...).
const machine = setup({
states: {
idle: {
schemas: { context: z.object({ user: z.null() }) }
},
success: {
schemas: { context: z.object({ user: z.string() }) }
}
}
}).createMachine({
schemas: {
context: z.object({ user: z.string().nullable() }),
events: {
LOAD: z.object({})
}
},
initial: 'idle',
context: { user: null },
states: {
idle: {
on: {
LOAD: () => ({
target: 'success',
context: { user: 'Ada' }
})
}
},
success: {
entry: ({ context }) => {
context.user; // string
}
}
}
});
const actor = createActor(machine).start();
const snapshot = actor.getSnapshot();
if (snapshot.matches('success')) {
snapshot.context.user; // string
}
State-level schemas.input is also supported: input supplied on a transition or initial ({ target, input }) is typed in that state's entry/exit and transition functions via ({ input }), read from a snapshot with snapshot.getInputs() (keyed by state node id), and typed recursively for nested states.
#44 52970ea Thanks @pull! - Add choice states — a state that immediately routes to a target via a resolver function, returning the first matching transition config.
const machine = createMachine({
context: { userStatus: 'vip' },
initial: 'routing',
states: {
routing: {
type: 'choice',
choice: ({ context }) => {
if (context.userStatus === 'vip') return { target: 'vipFlow' };
return { target: 'standardFlow' };
}
},
vipFlow: {},
standardFlow: {}
}
});
A choice state must declare a choice function and must resolve to a target, and may not declare entry/exit/on/after/invoke — these throw at construction.
#44 52970ea Thanks @pull! - The send function returned by useMachine (@xstate/vue) and useActor (@xstate/svelte) is now typed as the actor's own send signature, matching actorRef.send's overloads.
Updated dependencies [52970ea, 021cc56, 52970ea, 52970ea, 52970ea, 52970ea, d9079cd, 52970ea, 52970ea, 52970ea, 52970ea, 52970ea, 96aee67, 52970ea, 021cc56, 52970ea]:
Previously, calling assertEvent inside a function whose event parameter was typed with a generic (e.g. function f (event: TEvent)) would compile, but
#5827 9b3a88f Thanks @AlexRixten! - fix(core): fix assertEvent narrowing when the event type is behind a generic type parameter
Previously, calling assertEvent inside a function whose event parameter was typed with a generic (e.g. function f<TEvent extends SomeEventUnion>(event: TEvent)) would compile, but every property access on event afterward would fail to type-check with a "Property does not exist" error. This is now fixed - assertEvent narrows generic event parameters the same way it narrows concrete ones, while still rejecting invalid event descriptors at compile time.
assertEvent also keeps narrowing events whose type field is a union of literals (e.g. { type: 'a' | 'b'; value: string }) when asserting one of those literals, for both concrete and generic event parameters.
Partial wildcard descriptors now preserve the bare prefix event in the narrowed type, matching runtime behavior. For example, assertEvent(event, 'FEEDBACK.*') keeps both FEEDBACK and FEEDBACK.GOOD, so accessing a payload specific to FEEDBACK.GOOD requires further narrowing. This also applies to ExtractEvent and event types inferred for partial wildcard transitions.
### Patch Changes - #5792 `78431d6` Thanks @saadkhantareen! - Fixed child actors not being stopped when a machine errors because of an unhandled error
78431d6 Thanks @saadkhantareen! - Fixed child actors not being stopped when a machine errors because of an unhandled error from an invoked actor. The remaining invoked and spawned actors are now stopped (and their cleanup functions are called) before the machine settles in the error state, instead of being left running as orphans.### Patch Changes - #5718 `015dc23` Thanks @davidkpiano! - Fixed metadata types in generic history values, snapshot nodes, and directed graph results.
015dc23 Thanks @davidkpiano! - Fixed metadata types in generic history values, snapshot nodes, and directed graph results. These containers now accept arbitrary state and transition metadata consistently with AnyStateNode and AnyTransitionDefinition, avoiding unsafe-type warnings when inspecting machines through generic APIs.```ts declare const machine: AnyStateMachine;
#5712 8614c4d Thanks @crishoj! - AnyStateNode and AnyStateNodeDefinition now widen the TStateMeta and TTransitionMeta parameters that were added to StateNode and StateNodeDefinition in 5.33.0. Those parameters default to MetaObject, while the nodes of an AnyStateMachine have them as any, so tooling that tracks any (such as @typescript-eslint's no-unsafe-argument and no-unsafe-return) reported every node read off an untyped machine as unsafe:
declare const machine: AnyStateMachine;
// StateNode<any, any, any, any> passed to StateNode<any, any, MetaObject, MetaObject>
takesStateNode(machine.root);
AnyTransitionDefinition was widened along with the new parameters; these two were missed.
`ts const machine = setup({ types: { meta: {} as { label: string }, transitionMeta: {} as { trackingId: number } } }).createMachine({ meta: { label: '
#5700 6d8c317 Thanks @davidkpiano! - State and transition metadata can now use separate types:
const machine = setup({
types: {
meta: {} as { label: string },
transitionMeta: {} as { trackingId: number }
}
}).createMachine({
meta: { label: 'Root' },
on: {
NEXT: { meta: { trackingId: 42 } }
}
});
When transitionMeta is omitted, types.meta continues to apply its type to
both state and transition metadata.
### Patch Changes - #5678 `397b425` Thanks @davidkpiano! - Machine snapshots now retain their machine-specific methods when initialization fails, so m
397b425 Thanks @davidkpiano! - Machine snapshots now retain their machine-specific methods when initialization fails, so methods such as snapshot.matches(...) remain available on error snapshots.### Patch Changes - #5603 `345e04c` Thanks @xianjianlf2! - Sending an event to a stopped actor no longer throws when the event contains unserializable
345e04c Thanks @xianjianlf2! - Sending an event to a stopped actor no longer throws when the event contains unserializable data (e.g. circular references). Previously, the development-only warning that an event was sent to a stopped actor used JSON.stringify on the event, which could throw and mask the intended warning. The warning is now emitted safely regardless of the event's contents.```ts const machine = createMachine({ initial: 'off', states: { off: { on: { GO: 'on.hist' } }, on: { type: 'parallel', states: { regA: { initial: 'a1
#5589 e913eeb Thanks @spokodev! - Fixed a bug where targeting a history state that is a direct child of a parallel state would silently do nothing when that parallel state had not been visited yet and the history state had no default target. The machine now enters the parallel state's initial configuration, matching the behavior of history states inside compound states.
const machine = createMachine({
initial: 'off',
states: {
off: { on: { GO: 'on.hist' } },
on: {
type: 'parallel',
states: {
regA: { initial: 'a1', states: { a1: {}, a2: {} } },
regB: { initial: 'b1', states: { b1: {}, b2: {} } },
hist: { type: 'history', history: 'deep' }
}
}
}
});
const actor = createActor(machine).start();
actor.send({ type: 'GO' });
actor.getSnapshot().value; // { on: { regA: 'a1', regB: 'b1' } }
Root cause: createInertActorScope used createActor(logic) internally, which eagerly ran getInitialSnapshot during construction and registered any syst
#5575 830db8b Thanks @JSap0914! - Fixed initialTransition (and transition) throwing "Actor with system ID '...' already exists" when the machine contains an invoke with a systemId.
Root cause: createInertActorScope used createActor(logic) internally, which eagerly ran getInitialSnapshot during construction and registered any systemId-carrying child actors in the system. When the caller then ran getInitialSnapshot (or transition) via the returned scope, the same system was reused, causing the duplicate-registration error.
Fix: After creating the internal actor, createInertActorScope now replaces the actor's system reference with a freshly-created system. Child actors spawned by the subsequent caller-driven getInitialSnapshot / transition invocation therefore register into a clean system with no pre-existing entries.
const machine = createMachine({
initial: 'idle',
states: {
idle: {
invoke: {
src: fromPromise(async () => 42),
systemId: 'myActor' // previously caused: "Actor with system ID 'myActor' already exists"
}
}
}
});
// Now works correctly — returns [snapshot, actions] without throwing
const [snapshot, actions] = initialTransition(machine);
#5585 a551a2b Thanks @RubenFricke! - Add missing https:// protocol to the Stately Studio link in the README
When a state has both an exact event descriptor (e.g. "foo.bar") and a matching wildcard descriptor (e.g. "foo.*"), transitions from the exact descrip
#5548 8a53531 Thanks @JSap0914! - fix(core): fall back to wildcard event descriptors when an exact descriptor's guard fails
When a state has both an exact event descriptor (e.g. "foo.bar") and a matching wildcard descriptor (e.g. "foo.*"), transitions from the exact descriptor are now tried first; if all their guards fail, matching wildcard descriptor transitions are tried as fallback. Previously, the presence of an exact match would prevent any wildcard fallback from being considered, leaving the machine in its current state when the exact descriptor's guard failed.
### Patch Changes - #5516 `41c0a5a` Thanks @joshuaellis! - fix(core): resolve children snapshot union pollution for typed invoke
41c0a5a Thanks @joshuaellis! - fix(core): resolve children snapshot union pollution for typed invoke### Minor Changes - #5512 `063416d` Thanks @davidkpiano! - Export InspectedTransitionEvent from xstate.
063416d Thanks @davidkpiano! - Export InspectedTransitionEvent from xstate.`ts const machine = setup({ guards: { isReady: ({ context }) => context.ready } }).createMachine({ states: { review: { id: 'review', route: { guard: '
#5525 f79ea13 Thanks @davidkpiano! - Fixed route transition guards so named guards registered with setup({ guards }) are resolved for route.guard.
const machine = setup({
guards: {
isReady: ({ context }) => context.ready
}
}).createMachine({
states: {
review: {
id: 'review',
route: {
guard: 'isReady'
}
}
}
});
```ts import { mapState } from 'xstate';
#5429 9d9c1fe Thanks @davidkpiano! - Add mapState(snapshot, mapper) to map a snapshot to values based on active state(s).
import { mapState } from 'xstate';
const results = mapState(snapshot, {
states: {
loading: { map: () => 'Loading...' },
success: { map: (snap) => snap.context.data },
error: { map: (snap) => snap.context.error.message }
}
});
console.log(results);
// E.g. if snapshot.value === 'loading', then:
// [
// { stateNode: { key: 'loading' }, result: 'Loading...' }
// ]
#5430 e543599 Thanks @davidkpiano! - Add maxIterations option to configure the maximum number of microsteps allowed before throwing an infinite loop error. The default is Infinity (no limit) to avoid breaking existing machines.
You can configure it when creating a machine:
const machine = createMachine({
// ... machine config
options: {
maxIterations: 1000 // set a limit to enable infinite loop detection
}
});
This makes it possible to opt into enabled-only traversal for machine snapshots, such as when you only want to explore events that currently pass guar
#5493 871857d Thanks @davidkpiano! - Add a filterEvents option to xstate/graph traversal helpers and
createTestModel(...) to control which events should be explored from each
state.
This makes it possible to opt into enabled-only traversal for machine snapshots, such as when you only want to explore events that currently pass guards:
import { createTestModel } from 'xstate/graph';
const model = createTestModel(machine);
const paths = model.getSimplePaths({
filterEvents: (state, event) => state.can(event)
});
```ts const actor = createActor(machine); actor.start();
#5299 ca8306f Thanks @Uniqen! - Add actor.select(selector, equalityFn?) method to derive a Readable<TSelected> from an actor's snapshot. The returned object has .subscribe() (only emits when the selected value changes, using Object.is by default) and .get() for synchronous access.
const actor = createActor(machine);
actor.start();
const count = actor.select((snap) => snap.context.count);
count.get(); // current value
count.subscribe((value) => {
console.log(value); // only fires when count changes
});
```ts const machine = setup({}).createMachine({ id: 'app', initial: 'home', states: { home: { id: 'home', route: {} }, dashboard: { initial: 'overview
#4184 a741fe7 Thanks @davidkpiano! - Added routable states. States with route: {} and an explicit id can be navigated to from anywhere via a single { type: 'xstate.route', to: '#id' } event.
const machine = setup({}).createMachine({
id: 'app',
initial: 'home',
states: {
home: { id: 'home', route: {} },
dashboard: {
initial: 'overview',
states: {
overview: { id: 'overview', route: {} },
settings: { id: 'settings', route: {} }
}
}
}
});
const actor = createActor(machine).start();
// Route directly to deeply nested state from anywhere
actor.send({ type: 'xstate.route', to: '#settings' });
Routes support guards for conditional navigation:
settings: {
id: 'settings',
route: {
guard: ({ context }) => context.role === 'admin'
}
}
ad809a0 Thanks @davidkpiano! - Fix: export types so setup() declaration emit works (fixes #5462)```ts import { createMachine, getInitialMicrosteps, getMicrosteps } from 'xstate';
#5457 287b51e Thanks @davidkpiano! - Add getInitialMicrosteps(…) and getMicrosteps(…) functions that return an array of [snapshot, actions] tuples for each microstep in a transition.
import { createMachine, getInitialMicrosteps, getMicrosteps } from 'xstate';
const machine = createMachine({
initial: 'a',
states: {
a: {
entry: () => console.log('enter a'),
on: {
NEXT: 'b'
}
},
b: {
entry: () => console.log('enter b'),
always: 'c'
},
c: {}
}
});
// Get microsteps from initial transition
const initialMicrosteps = getInitialMicrosteps(machine);
// Returns: [
// [snapshotA, [entryActionA]]
// ]
// Get microsteps from a transition
const microsteps = getMicrosteps(machine, initialMicrosteps[0][0], {
type: 'NEXT'
});
// Returns: [
// [snapshotB, [entryActionB]],
// [snapshotC, []]
// ]
// Each microstep is a tuple of [snapshot, actions]
for (const [snapshot, actions] of microsteps) {
console.log('State:', snapshot.value);
console.log('Actions:', actions.length);
}
```ts import { getNextTransitions } from 'xstate';
#5406 703c3a1 Thanks @davidkpiano! - Add getNextTransitions(state) utility to get all transitions available from current state.
import { getNextTransitions } from 'xstate';
// ...
const state = actor.getSnapshot();
const transitions = getNextTransitions(state);
transitions.forEach((t) => {
console.log(`Event: ${t.eventType}, Source: ${t.source.key}`);
});
### Patch Changes - #5440 `e36e299` Thanks @davidkpiano! - Fix systemId cleanup for nested children on stopChild
e36e299 Thanks @davidkpiano! - Fix systemId cleanup for nested children on stopChild``ts // Matches any event with a type that starts with FEEDBACK. assertEvent(event, 'FEEDBACK.*'); ``
#5422 329297b Thanks @davidkpiano! - Add partial descriptor support to assertEvent(…)
// Matches any event with a type that starts with `FEEDBACK.`
assertEvent(event, 'FEEDBACK.*');
2eb8274 Thanks @assertnotnull! - Fix a bug in Cordova when iterating an empty Map```ts import { setup, not, and } from 'xstate';
#5371 b8ec3b1 Thanks @davidkpiano! - Add setup.extend() method to incrementally extend machine setup configurations with additional actions, guards, and delays. This enables composable and reusable machine setups where extended actions, guards, and delays can reference base actions, guards, and delays and support chaining multiple extensions:
import { setup, not, and } from 'xstate';
const baseSetup = setup({
guards: {
isAuthenticated: () => true,
hasPermission: () => false
}
});
const extendedSetup = baseSetup.extend({
guards: {
// Type-safe guard references
isUnauthenticated: not('isAuthenticated'),
canAccess: and(['isAuthenticated', 'hasPermission'])
}
});
// Both base and extended guards are available
extendedSetup.createMachine({
on: {
LOGIN: {
guard: 'isAuthenticated',
target: 'authenticated'
},
LOGOUT: {
guard: 'isUnauthenticated',
target: 'unauthenticated'
}
}
});
```ts const childMachine = createMachine({}); const machine = createMachine({ // ... invoke: [ { src: childMachine, systemId: 'test' } ] }); const sys
#5387 53dd7f1 Thanks @farskid! - Adds system.getAll that returns a record of running actors within the system by their system id
const childMachine = createMachine({});
const machine = createMachine({
// ...
invoke: [
{
src: childMachine,
systemId: 'test'
}
]
});
const system = createActor(machine);
system.getAll(); // { test: ActorRefFrom<typeof childMachine> }
`ts const actor = createActor(machine, { systemId: 'test' }); actor.systemId; // 'test' `
#5379 98f9ddd Thanks @davidkpiano! - Make actor.systemId public:
const actor = createActor(machine, { systemId: 'test' });
actor.systemId; // 'test'
#5380 e7e5e44 Thanks @Nirajkashyap! - fix: remove 'eventType' from required fields in initialTransitionObject
createAction(fn) – create type-safe custom actions
#5367 76c857e Thanks @davidkpiano! - Add type-bound action helpers to setup():
createAction(fn) – create type-safe custom actionssetup().assign(...), setup().sendTo(...), setup().raise(...), setup().log(...), setup().cancel(...), setup().stopChild(...), setup().enqueueActions(...), setup().emit(...), setup().spawnChild(...) – setup-scoped helpers that are fully typed to the setup's context/events/actors/guards/delays/emitted.These helpers return actions that are bound to the specific setup() they were created from and can be used directly in the machine produced by that setup.
const machineSetup = setup({
types: {} as {
context: {
count: number;
};
events: { type: 'inc'; value: number } | { type: 'TEST' };
emitted: { type: 'PING' };
}
});
// Custom action
const action = machineSetup.createAction(({ context, event }) => {
console.log(context.count, event.value);
});
// Type-bound built-ins (no wrapper needed)
const increment = machineSetup.assign({
count: ({ context }) => context.count + 1
});
const raiseTest = machineSetup.raise({ type: 'TEST' });
const ping = machineSetup.emit({ type: 'PING' });
const batch = machineSetup.enqueueActions(({ enqueue, check }) => {
if (check(() => true)) {
enqueue(increment);
}
});
const machine = machineSetup.createMachine({
context: { count: 0 },
entry: [action, increment, raiseTest, ping, batch]
});
```ts const lightMachineSetup = setup({ // ... });
#5364 15e15b5 Thanks @davidkpiano! - Added .createStateConfig(…) to the setup API. This makes it possible to create state configs that are strongly typed and modular.
const lightMachineSetup = setup({
// ...
});
const green = lightMachineSetup.createStateConfig({
//...
});
const yellow = lightMachineSetup.createStateConfig({
//...
});
const red = lightMachineSetup.createStateConfig({
//...
});
const machine = lightMachineSetup.createMachine({
initial: 'green',
states: {
green,
yellow,
red
}
});
`ts actor.on('event', () => { // Will no longer crash the actor throw new Error('oops'); }); `
#5351 71387ff Thanks @davidkpiano! - Fix: Emit callback errors no longer crash the actor
actor.on('event', () => {
// Will no longer crash the actor
throw new Error('oops');
});
### Patch Changes - #5315 `9a0ae82` Thanks @sfc-gh-dperezalvarez! - Exported InspectedActionEvent type
9a0ae82 Thanks @sfc-gh-dperezalvarez! - Exported InspectedActionEvent type```ts import { createMachine } from 'xstate'; import { getShortestPaths } from 'xstate/graph';
#5287 e07a7cd8462473188a0fb646a965e61be1ce6ae3 Thanks @davidkpiano! - The graph and model-based testing utilities from @xstate/graph (and @xstate/test previously) were moved to the core xstate package.
import { createMachine } from 'xstate';
import { getShortestPaths } from 'xstate/graph';
const machine = createMachine({
// ...
});
const paths = getShortestPaths(machine, {
fromState: 'a',
toState: 'b'
});
### Patch Changes - #5289 `479c74b83fa77c57c48f54cf0e9dcfab5fe6cae5` Thanks @ebadyz! - Removed outdated context parameter reference from provide metho
479c74b83fa77c57c48f54cf0e9dcfab5fe6cae5 Thanks @ebadyz! - Removed outdated context parameter reference from provide method documentation.### Patch Changes - #5269 `b453b2d72ba12d0fe46a995f9ccced8000fd0cc9` Thanks @chladog! - Add proper history value persistence and restoration
b453b2d72ba12d0fe46a995f9ccced8000fd0cc9 Thanks @chladog! - Add proper history value persistence and restoration### Patch Changes - #5170 `d99df1d8f4fe49145c9974465b65028bf19b365f` Thanks @Andarist! - Improved compatibility of inferred types in projects with exa
d99df1d8f4fe49145c9974465b65028bf19b365f Thanks @Andarist! - Improved compatibility of inferred types in projects with exactOptionalPropertyTypes enabled```ts const childMachine = createMachine({ types: { input: {} as { value: number } } });
#5139 bf6119a7310a878afbf4f5b01f5e24288f9a0f16 Thanks @SandroMaglione! - Make spawn input required when defined inside referenced actor:
const childMachine = createMachine({
types: { input: {} as { value: number } }
});
const machine = createMachine({
types: {} as { context: { ref: ActorRefFrom<typeof childMachine> } },
context: ({ spawn }) => ({
ref: spawn(
childMachine,
// Input is now required!
{ input: { value: 42 } }
)
})
});
```ts import { transition } from 'xstate';
#4954 8c4b70652acaef2702f32435362e4755679a516d Thanks @davidkpiano! - Added a new transition function that takes an actor logic, a snapshot, and an event, and returns a tuple containing the next snapshot and the actions to execute. This function is a pure function and does not execute the actions itself. It can be used like this:
import { transition } from 'xstate';
const [nextState, actions] = transition(actorLogic, currentState, event);
// Execute actions as needed
Added a new initialTransition function that takes an actor logic and an optional input, and returns a tuple containing the initial snapshot and the actions to execute from the initial transition. This function is also a pure function and does not execute the actions itself. It can be used like this:
import { initialTransition } from 'xstate';
const [initialState, actions] = initialTransition(actorLogic, input);
// Execute actions as needed
These new functions provide a way to separate the calculation of the next snapshot and actions from the execution of those actions, allowing for more control and flexibility in the transition process.
### Patch Changes - #5079 `25963966c394fc904dc9b701a420b6e204ebe7f7` Thanks @davidkpiano! - The inspection event interfaces now expect ActorRefLike in
25963966c394fc904dc9b701a420b6e204ebe7f7 Thanks @davidkpiano! - The inspection event interfaces now expect ActorRefLike instead of AnyActorRef### Patch Changes - #5055 `ad38c35c37` Thanks @SandroMaglione! - Exported RequiredActorOptionsKeys type meant to be used by integration packages like
ad38c35c37 Thanks @SandroMaglione! - Exported RequiredActorOptionsKeys type meant to be used by integration packages like @xstate/react```ts const machine = setup({}).createMachine({ initial: 'green', states: { green: {}, yellow: {}, red: { initial: 'walk', states: { walk: {}, wait: {
#5042 54c9d9e6a4 Thanks @boneskull! - waitFor() now accepts a {signal: AbortSignal} in WaitForOptions
#5006 1ab974547f Thanks @davidkpiano! - The state value typings for setup state machine actors (setup({}).createMachine({ ... })) have been improved to represent the actual expected state values.
const machine = setup({}).createMachine({
initial: 'green',
states: {
green: {},
yellow: {},
red: {
initial: 'walk',
states: {
walk: {},
wait: {},
stop: {}
}
},
emergency: {
type: 'parallel',
states: {
main: {
initial: 'blinking',
states: {
blinking: {}
}
},
cross: {
initial: 'blinking',
states: {
blinking: {}
}
}
}
}
}
});
const actor = createActor(machine).start();
const stateValue = actor.getSnapshot().value;
if (stateValue === 'green') {
// ...
} else if (stateValue === 'yellow') {
// ...
} else if ('red' in stateValue) {
stateValue;
// {
// red: "walk" | "wait" | "stop";
// }
} else {
stateValue;
// {
// emergency: {
// main: "blinking";
// cross: "blinking";
// };
// }
}
#5054 853f6daa0b Thanks @davidkpiano! - The CallbackLogicFunction type (previously InvokeCallback) is now exported. This is the callback function that you pass into fromCallback(callbackLogicFn) to create an actor from a callback function.
import { type CallbackLogicFunction } from 'xstate';
// ...
### Patch Changes - #5039 `d6df8fb470` Thanks @Andarist! - Fixed an inference issue that prevented emit used directly in setup (or bare createMachine)
d6df8fb470 Thanks @Andarist! - Fixed an inference issue that prevented emit used directly in setup (or bare createMachine) to benefit from types.emitted types.### Patch Changes - #5034 `7bed484c38` Thanks @davidkpiano! - Fix EventFrom and ContextFrom types
7bed484c38 Thanks @davidkpiano! - Fix EventFrom and ContextFrom types### Patch Changes - #5029 `88bd87ab41` Thanks @davidkpiano! - Revert ActorRefFrom change - #5011 `a275d274de` Thanks @davidkpiano! - There is a new ty
#5029 88bd87ab41 Thanks @davidkpiano! - Revert ActorRefFrom change
#5011 a275d274de Thanks @davidkpiano! - There is a new type helper: ActorRefFromLogic<TLogic>. This type is a stricter form of ActorRefFrom<TLogic> that only accepts actor logic types. See https://github.com/statelyai/xstate/issues/4997 for more details.
### Patch Changes - #5009 `51d4c4fc5` Thanks @davidkpiano! - The internal types for StateMachine<...> have been improved so that all type params are r
51d4c4fc5 Thanks @davidkpiano! - The internal types for StateMachine<...> have been improved so that all type params are required, to prevent errors when using the types. This fixes weird issues like #5008.```ts const machine = setup({ // ... }).createMachine({ id: 'root', initial: 'parentState', states: { parentState: { meta: {}, initial: 'childState',
#4979 a0e9ebcef Thanks @davidkpiano! - State IDs are now strongly typed as keys of snapshot.getMeta() for state machine actor snapshots.
const machine = setup({
// ...
}).createMachine({
id: 'root',
initial: 'parentState',
states: {
parentState: {
meta: {},
initial: 'childState',
states: {
childState: {
meta: {}
},
stateWithId: {
id: 'state with id',
meta: {}
}
}
}
}
});
const actor = createActor(machine);
const metaValues = actor.getSnapshot().getMeta();
// Auto-completed keys:
metaValues.root;
metaValues['root.parentState'];
metaValues['root.parentState.childState'];
metaValues['state with id'];
// @ts-expect-error
metaValues['root.parentState.stateWithId'];
// @ts-expect-error
metaValues['unknown state'];
9877d548b Thanks @davidkpiano! - Fix an issue where clearTimeout(undefined) was sometimes being called, which can cause errors for some clock implementations. See https://github.com/statelyai/xstate/issues/5001 for details.```js import { createMachine, enqueueActions } from 'xstate';
#4996 5be796cd2 Thanks @ronvoluted! - The actor snapshot status type ('active' | 'done' | 'error' | 'stopped') is now exposed as SnapshotStatus
#4981 c4ae156b2 Thanks @davidkpiano! - Added sendParent to the enqueueActions feature. This allows users to enqueue actions that send events to the parent actor within the enqueueActions block.
import { createMachine, enqueueActions } from 'xstate';
const childMachine = createMachine({
entry: enqueueActions(({ enqueue }) => {
enqueue.sendParent({ type: 'CHILD_READY' });
})
});
Each type represents ActorRef narrowed to the corresponding type of logic (the type of self within the actor's logic):
#4976 452bce71e Thanks @with-heart! - Added exports for actor logic-specific ActorRef types: CallbackActorRef, ObservableActorRef, PromiseActorRef, and TransitionActorRef.
Each type represents ActorRef narrowed to the corresponding type of logic (the type of self within the actor's logic):
CallbackActorRef: actor created by fromCallback
import { fromCallback, createActor } from 'xstate';
/** The events the actor receives. */
type Event = { type: 'someEvent' };
/** The actor's input. */
type Input = { name: string };
/** Actor logic that logs whenever it receives an event of type `someEvent`. */
const logic = fromCallback<Event, Input>(({ self, input, receive }) => {
self;
// ^? CallbackActorRef<Event, Input>
receive((event) => {
if (event.type === 'someEvent') {
console.log(`${input.name}: received "someEvent" event`);
// logs 'myActor: received "someEvent" event'
}
});
});
const actor = createActor(logic, { input: { name: 'myActor' } });
// ^? CallbackActorRef<Event, Input>
ObservableActorRef: actor created by fromObservable and fromEventObservable
import { fromObservable, createActor } from 'xstate';
import { interval } from 'rxjs';
/** The type of the value observed by the actor's logic. */
type Context = number;
/** The actor's input. */
type Input = { period?: number };
/**
* Actor logic that observes a number incremented every `input.period`
* milliseconds (default: 1_000).
*/
const logic = fromObservable<Context, Input>(({ input, self }) => {
self;
// ^? ObservableActorRef<Event, Input>
return interval(input.period ?? 1_000);
});
const actor = createActor(logic, { input: { period: 2_000 } });
// ^? ObservableActorRef<Event, Input>
PromiseActorRef: actor created by fromPromise
import { fromPromise, createActor } from 'xstate';
/** The actor's resolved output. */
type Output = string;
/** The actor's input. */
type Input = { message: string };
/** Actor logic that fetches the url of an image of a cat saying `input.message`. */
const logic = fromPromise<Output, Input>(async ({ input, self }) => {
self;
// ^? PromiseActorRef<Output, Input>
const data = await fetch(`https://cataas.com/cat/says/${input.message}`);
const url = await data.json();
return url;
});
const actor = createActor(logic, { input: { message: 'hello world' } });
// ^? PromiseActorRef<Output, Input>
TransitionActorRef: actor created by fromTransition
import { fromTransition, createActor, type AnyActorSystem } from 'xstate';
/** The actor's stored context. */
type Context = {
/** The current count. */
count: number;
/** The amount to increase `count` by. */
step: number;
};
/** The events the actor receives. */
type Event = { type: 'increment' };
/** The actor's input. */
type Input = { step?: number };
/**
* Actor logic that increments `count` by `step` when it receives an event of
* type `increment`.
*/
const logic = fromTransition<Context, Event, AnyActorSystem, Input>(
(state, event, actorScope) => {
actorScope.self;
// ^? TransitionActorRef<Context, Event>
if (event.type === 'increment') {
return {
...state,
count: state.count + state.step
};
}
return state;
},
({ input, self }) => {
self;
// ^? TransitionActorRef<Context, Event>
return {
count: 0,
step: input.step ?? 1
};
}
);
const actor = createActor(logic, { input: { step: 10 } });
// ^? TransitionActorRef<Context, Event>
#4949 8aa4c2b90 Thanks @davidkpiano! - The TypeGen-related types have been removed from XState, simplifying the internal types without affecting normal XState usage.
```ts const actor = createActor(someMachine);
#4936 c58b36dc3 Thanks @davidkpiano! - Inspecting an actor system via actor.system.inspect(ev => …) now accepts a function or observer, and returns a subscription:
const actor = createActor(someMachine);
const sub = actor.system.inspect((inspectionEvent) => {
console.log(inspectionEvent);
});
// Inspection events will be logged
actor.start();
actor.send({ type: 'anEvent' });
// ...
sub.unsubscribe();
// Will no longer log inspection events
actor.send({ type: 'someEvent' });
#4942 9caaa1f70 Thanks @boneskull! - DoneActorEvent and ErrorActorEvent now contain property actorId, which refers to the ID of the actor the event refers to.
#4935 2ac08b700 Thanks @davidkpiano! - All actor logic creators now support emitting events:
Promise actors
const logic = fromPromise(async ({ emit }) => {
// ...
emit({
type: 'emitted',
msg: 'hello'
});
// ...
});
Transition actors
const logic = fromTransition((state, event, { emit }) => {
// ...
emit({
type: 'emitted',
msg: 'hello'
});
// ...
return state;
}, {});
Observable actors
const logic = fromObservable(({ emit }) => {
// ...
emit({
type: 'emitted',
msg: 'hello'
});
// ...
});
Callback actors
const logic = fromCallback(({ emit }) => {
// ...
emit({
type: 'emitted',
msg: 'hello'
});
// ...
});
417f35a11 Thanks @boneskull! - Expose type UnknownActorRef for use when calling getSnapshot() on an unknown ActorRef.### Patch Changes - #4932 `71a7f8692` Thanks @davidkpiano! - Actors with emitted events should no longer cause type issues:
71a7f8692 Thanks @davidkpiano! - Actors with emitted events should no longer cause type issues: https://github.com/statelyai/xstate/issues/4931`ts actor.on('*', (emitted) => { console.log(emitted); // Any emitted event }); `
#4905 dbeafeb25 Thanks @davidkpiano! - You can now use a wildcard to listen for any emitted event from an actor:
actor.on('*', (emitted) => {
console.log(emitted); // Any emitted event
});
`ts const logic = fromPromise(({ signal }) => fetch('https://api.example.com', { signal }) ); `
#4832 148d8fcef Thanks @cevr! - fromPromise now passes a signal into its creator function.
const logic = fromPromise(({ signal }) =>
fetch('https://api.example.com', { signal })
);
This will be called whenever the state transitions before the promise is resolved. This is useful for cancelling the promise if the state changes.
#4876 3f6a73b56 Thanks @davidkpiano! - XState will now warn when calling built-in actions like assign, sendTo, raise, emit, etc. directly inside of a custom action. See https://stately.ai/docs/actions#built-in-actions for more details.
const machine = createMachine({
entry: () => {
// Will warn:
// "Custom actions should not call \`assign()\` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details."
assign({
// ...
});
}
});
```ts const machine = setup({ types: { meta: {} as { layout: string; } } }).createMachine({ initial: 'home', states: { home: { meta: { layout: 'full'
#4863 0696adc21 Thanks @davidkpiano! - Meta objects for state nodes and transitions can now be specified in setup({ types: … }):
const machine = setup({
types: {
meta: {} as {
layout: string;
}
}
}).createMachine({
initial: 'home',
states: {
home: {
meta: {
layout: 'full'
}
}
}
});
const actor = createActor(machine).start();
actor.getSnapshot().getMeta().home;
// => { layout: 'full' }
// if in "home" state
`ts const machine = setup({ actors: { existingActor: fromPromise(async () => { // ... }) } }).createMachine({ invoke: { src: fromPromise(async () => {
#4806 f4e0ec48c Thanks @davidkpiano! - Inline actor logic is now permitted when named actors are present. Defining inline actors will no longer cause a TypeScript error:
const machine = setup({
actors: {
existingActor: fromPromise(async () => {
// ...
})
}
}).createMachine({
invoke: {
src: fromPromise(async () => {
// Inline actor
})
// ...
}
});
One column per quarter.