xstate
5.33.4 · 7 Nov 2026MIT9M / weekRepositoryHomepagenpmAtom feed
201 stable releases, newest first, by release line. Notes are quoted as the maintainers published them.
- 5.x · latest line
5.10.0
9 Apr 2024The
clockandloggerspecified in theoptionsobject ofcreateActor(logic, options)will now propagate to all actors created within the same actor system.import { setup, log, createActor } from 'xstate'; const childMachine = setup({ // ... }).createMachine({ // ... // Uses custom logger from root actor entry: log('something') }); const parentMachine = setup({ // ... }).createMachine({ // ... invoke: { src: childMachine } }); const actor = createActor(parentMachine, { logger: (...args) => { // custom logger for args } }); actor.start();
5.9.1
2 Mar 2024Add missing
emitexport
5.9.0
1 Mar 2024The new
emit(…)action creator emits events that can be received by listeners. Actors are now event emitters.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' // }Added support for
paramstoenqueueActions
5.8.2
28 Feb 2024Fixed a type issue that prevent
sendParentto be accepted bysetupwhendelaysstayed not configured.
5.8.1
27 Feb 2024Correctly use falsy outputs (instead of accidentally converting them to
undefined).
5.8.0
21 Feb 2024Revamped
setupand actions types to disallow usage of non-configured implementations
5.7.1
17 Feb 2024- Removed
Removed
thisfrom machine snapshot methods to fix issues with accessing those methods from union of actors and their snapshots.
5.7.0
16 Feb 2024An error will now be thrown if an incompatible state value is passed to
machine.resolveState({ value }).You can now inspect microsteps (
@xstate.microstep) and actions (@xstate.action):const machine = createMachine({ initial: 'a', states: { a: { on: { event: 'b' } }, b: { entry: 'someAction', always: 'c' }, c: {} } }); const actor = createActor(machine, { inspect: (inspEvent) => { if (inspEvent.type === '@xstate.microstep') { console.log(inspEvent.snapshot); // logs: // { value: 'a', … } // { value: 'b', … } // { value: 'c', … } console.log(inspEvent.event); // logs: // { type: 'event', … } } else if (inspEvent.type === '@xstate.action') { console.log(inspEvent.action); // logs: // { type: 'someAction', … } } } }); actor.start(); actor.send({ type: 'event' });
5.6.2
7 Feb 2024You can now import
getInitialSnapshot(…)fromxstatedirectly, which is useful for getting a mock of the initial snapshot when interacting with machines (or other actor logic) withoutcreateActor(…):import { getInitialSnapshot } from 'xstate'; import { someMachine } from './someMachine'; // Returns the initial snapshot (state) of the machine const initialSnapshot = getInitialSnapshot( someMachine, { name: 'Mateusz' } // optional input );
5.6.1
5 Feb 2024Fixed compatibility issue of the internal type definitions with TypeScript 5.0
Ensure that
InteropObservableandInteropSubscribableare present in the type definition file.Add
UnknownMachineConfigtype
5.6.0
29 Jan 2024createActorwill now error if the requiredinputis not given to it.The
schemasproperty insetup(...)is now passed through to the resulting machine. This property is meant to be used with future developer tooling, and is typed asunknownfor now.Fixed compatibility with the upcoming TypeScript 5.4
5.5.2
23 Jan 2024State IDs that have periods in them are now supported if those periods are escaped.
The motivation is that external tools, such as Stately Studio, may allow users to enter any text into the state ID field. This change allows those tools to escape periods in state IDs, so that they don't conflict with the internal path-based state IDs.
E.g. if a state ID of
"Loading..."is entered into the state ID field, instead of crashing either the external tool and/or the XState state machine, it should be converted by the tool to"Loading\\.\\.\\.", and those periods will be ignored by XState.
5.5.1
11 Jan 2024Fixed compatibility with older versions of integration packages.
5.5.0
10 Jan 2024Introduce
getNextSnapshot(...), which determines the next snapshot for the givenactorLogicbased on the givensnapshotandevent.If the
snapshotisundefined, the initial snapshot of theactorLogicis used.import { getNextSnapshot } from 'xstate'; import { trafficLightMachine } from './trafficLightMachine.ts'; const nextSnapshot = getNextSnapshot( trafficLightMachine, // actor logic undefined, // snapshot (or initial state if undefined) { type: 'TIMER' } ); // event object console.log(nextSnapshot.value); // => 'yellow' const nextSnapshot2 = getNextSnapshot( trafficLightMachine, // actor logic nextSnapshot, // snapshot { type: 'TIMER' } ); // event object console.log(nextSnapshot2.value); // =>'red'Allow
eventin transitions to be narrowed down even when its.typeis defined using a union.
5.4.1
24 Dec 2023Typegen-based types for detecting missing implementations have been removed internally.
5.4.0
22 Dec 2023contextfactories receiveselfnow so you can immediately pass that as part of the input to spawned actors.setup({ /* ... */ }).createMachine({ context: ({ spawn, self }) => { return { childRef: spawn('child', { input: { parent: self } }) }; } });
5.3.1
18 Dec 2023Update the argument object of
enqueueActions(...)to include theselfandsystemproperties:// ... entry: enqueueActions(({ self, system }) => { // ... });
5.3.0
13 Dec 2023Add
assertEvent(...)to help provide strong typings for events that can't be easily inferred, such as events inentryandexitactions, or ininvoke.input.The
assertEvent(event, 'someType')function will throw if the event is not the expected type. This ensures that theeventis guaranteed to have that type, and assumes that the event object has the expected payload (naturally enforced by TypeScript).// ... entry: ({ 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' } }, exit: ({ event }) => { assertEvent(event, 'doNothing'); // event is { type: 'doNothing' } }Fixed an issue with ancestors of the default history target that lie outside of the transition domain being incorrectly entered.
5.2.1
9 Dec 2023Update README.md
5.2.0
7 Dec 2023Introduce
toPromise(actor), which creates a promise from anactorthat resolves with the actor snapshot'soutputwhen done, or rejects with the actor snapshot'serrorwhen it fails.import { createMachine, createActor, toPromise } from 'xstate'; const machine = createMachine({ // ... states: { // ... done: { type: 'final', output: 42 } } }); const actor = createActor(machine); actor.start(); const output = await toPromise(actor); console.log(output); // => 42Fixed an issue with
spawnwithinassignnot returning a narrowed downActorReftype on TypeScrip 5.0Fixed an issue that caused a
completelistener to be called instead of theerrorone when the actor was subscribed after being stopped.
5.1.0
6 Dec 2023Fix higher-level logic for state machine logic
Patch Changes
Fix higher-level logic for state machine logic
5.0.2
4 Dec 2023Fixed defining
actorswithinputwithinsetup.
5.0.1
4 Dec 2023- Deprecated
Flag that docs in this repo are deprecated in favour of docs at stately.ai/docs/xstate
5.0.0
1 Dec 2023- Breaking
If context types are specified in the machine config, the
contextproperty will now be required:// ❌ TS error createMachine({ types: {} as { context: { count: number }; } // Missing context property }); // ✅ OK createMachine({ types: {} as { context: { count: number }; }, context: { count: 0 } }); - Breaking
The third argument of
machine.transition(state, event)has been removed. Thecontextshould always be given as part of thestate.// ... initial: { target: 'someTarget', actions: [/* initial actions */] }This shouldn't change the behavior for most state machines. To maintain the previous behavior, ensure that
assign()actions are defined before any other actions. - Breaking
An error will be thrown if an
initialstate key is not specified for compound state nodes. For example:const lightMachine = createMachine({ id: 'light', initial: 'green', states: { green: {}, yellow: {}, red: { // Forgotten initial state: // initial: 'walk', states: { walk: {}, wait: {} } } } });You will get the error:
No initial state specified for state node "#light.red". Try adding { initial: "walk" } to the state config.
Major Changes
- Breaking
If context types are specified in the machine config, the
contextproperty will now be required:// ❌ TS error createMachine({ types: {} as { context: { count: number }; } // Missing context property }); // ✅ OK createMachine({ types: {} as { context: { count: number }; }, context: { count: 0 } }); - Breaking
The third argument of
machine.transition(state, event)has been removed. Thecontextshould always be given as part of thestate.There is a new method:
machine.microstep(snapshot, event)which returns the resulting intermediateMachineSnapshotobject that represents a single microstep being taken when transitioning fromsnapshotvia theevent. This is theMachineSnapshotthat does not take into account transient transitions nor raised events, and is useful for debugging.The
state.eventsproperty has been removed from theStateobjectThe
state.historyValueproperty now more closely represents the original SCXML algorithm, and is a mapping of state node IDs to their historic descendent state nodes. This is used for resolving history states, and should be considered internal.The
stateNode.isTransientproperty is removed fromStateNode.The
.initialproperty of a state node config object can now contain executable content (i.e., actions):
// ... initial: { target: 'someTarget', actions: [/* initial actions */] }Assign actions (via
assign()) will now be executed "in order", rather than automatically prioritized. They will be evaluated after previously defined actions are evaluated, and actions that read fromcontextwill have those intermediate values applied, rather than the final resolved value of allassign()actions taken, which was the previous behavior.
This shouldn't change the behavior for most state machines. To maintain the previous behavior, ensure that
assign()actions are defined before any other actions. - Breaking
An error will be thrown if an
initialstate key is not specified for compound state nodes. For example:const lightMachine = createMachine({ id: 'light', initial: 'green', states: { green: {}, yellow: {}, red: { // Forgotten initial state: // initial: 'walk', states: { walk: {}, wait: {} } } } });You will get the error:
No initial state specified for state node "#light.red". Try adding { initial: "walk" } to the state config. - Breaking
IDs for delayed events are no longer derived from event types so this won't work automatically:
entry: raise({ type: 'TIMER' }, { delay: 200 }); exit: cancel('TIMER');Please use explicit IDs:
entry: raise({ type: 'TIMER' }, { delay: 200, id: 'myTimer' }); exit: cancel('myTimer'); - Breaking
Removed
State#toStringsmethod. - Breaking
The machine's
contextis now restricted to anRecord<string, any>. This was the most common usage, but now the typings preventcontextfrom being anything but an object:const machine = createMachine({ // This will produce the TS error: // "Type 'string' is not assignable to type 'object | undefined'" context: 'some string' });If
contextisundefined, it will now default to an empty object{}. - Breaking
Actors are now always part of a "system", which is a collection of actors that can communicate with each other. Systems are implicitly created, and can be used to get and set references to any actor in the system via the
systemIdprop:const machine = createMachine({ // ... invoke: { src: emailMachine, // Registers `emailMachine` as `emailer` on the system systemId: 'emailer' } });const machine = createMachine({ // ... entry: assign({ emailer: (ctx, ev, { spawn }) => spawn(emailMachine, { systemId: 'emailer' }) }) });Any invoked/spawned actor that is part of a system will be able to reference that actor:
const anotherMachine = createMachine({ // ... entry: sendTo( (ctx, ev, { system }) => { return system.get('emailer'); }, { type: 'SEND_EMAIL', subject: 'Hello', body: 'World' } ) });Each top-level
createActor(...)call creates a separate implicit system. In this example example,actor1andactor2are part of different systems and are unrelated:// Implicit system const actor1 = createActor(machine).start(); // Another implicit system const actor2 = createActor(machine).start();
- Breaking
externalproperty on transitions has been renamed toreenter - Breaking
The
interpreter.onStop(...)method has been removed. Use an observer instead viaactorRef.subscribe({ complete() { ... } })instead. - Breaking
Removed
MachineSnapshot['nextEvents']. - Breaking
Renamed
machine.withConfig(...)tomachine.provide(...). - Breaking
Removed third parameter (context) from Machine's transition method. If you want to transition with a particular context value you should create appropriate
MachineSnapshotusingmachine.resolveState. So instead of this -machine.transition('green', { type: 'TIMER' }, { elapsed: 100 }), you should do this -machine.transition(machine.resolveState({ value: 'green', context: { elapsed: 100 } }), { type: 'TIMER' }). - Breaking
Sending a string event to
actorRef.send('some string')will now throw a proper error message. - Breaking
The
selfactor reference is now available in all action metas. This makes it easier to reference the "self"ActorRefso that actions such assendTocan include it in the event payload:// Sender actions: sendTo('somewhere', (ctx, ev, { self }) => ({ type: 'EVENT', ref: self })), // ... // Responder actions: sendTo((ctx, ev) => ev.ref, ...) - Breaking
isState/isStateConfigwere replaced byisMachineSnapshot. Similarly,AnyStatetype was deprecated and it's replaced byAnyMachineSnapshottype. - Breaking
All actor snapshots now have a consistent, predictable shape containing these common properties:
status:'active' | 'done' | 'error' | 'stopped'output: The output data of the actor when it has reachedstatus: 'done'error: The error thrown by the actor when it has reachedstatus: 'error'context: The context of the actor
This makes it easier to work with actors in a consistent way, and to inspect their snapshots.
const promiseActor = fromPromise(async () => { return 42; }); // Previously number | undefined // Now a snapshot object with { status, output, error, context } const promiseActorSnapshot = promiseActor.getSnapshot(); if (promiseActorSnapshot.status === 'done') { console.log(promiseActorSnapshot.output); // 42 } - Breaking
Restoring persisted state is now done by passing the state into the
snapshot: ...property of thecreateActoroptions argument:-interpret(machine).start(state); +createActor(machine, { snapshot }).start();The persisted snapshot is obtained from an actor by calling
actor.getPersistedSnapshot():const actor = createActor(machine).start(); const persistedSnapshot = actor.getPersistedSnapshot(); // ... const restoredActor = createActor(machine, { snapshot: persistedSnapshot }).start(); - Breaking
The
executeoption for an interpreted service has been removed. If you don't want to execute actions, it's recommended that you don't hardcode implementation details into the basemachinethat will be interpreted, and extend the machine'soptions.actionsinstead. By default, the interpreter will execute all actions according to SCXML semantics (immediately upon transition).Dev tools integration has been simplified, and Redux dev tools support is no longer the default. It can be included from
xstate/devTools/redux:
import { createActor } from 'xstate'; import { createReduxDevTools } from 'xstate/devTools/redux'; const service = createActor(someMachine, { devTools: createReduxDevTools({ // Redux Dev Tools options }) });By default, dev tools are attached to the global
window.__xstate__object:const service = createActor(someMachine, { devTools: true // attaches via window.__xstate__.register(service) });And creating your own custom dev tools adapter is a function that takes in the
actorRef:const myCustomDevTools = (actorRef) => { console.log('Got a actorRef!'); actorRef.subscribe((state) => { // ... }); }; const actorRef = createActor(someMachine, { devTools: myCustomDevTools });These handlers have been removed, as they are redundant and can all be accomplished with
.onTransition(...)and/or.subscribe(...):actorRef.onEvent()actorRef.onSend()actorRef.onChange()
The
actorRef.send(...)method no longer returns the next state. It is avoidfunction (fire-and-forget).The
actorRef.sender(...)method has been removed as redundant. UseactorRef.send(...)instead.
- Breaking
The output data on final states is now specified as
.outputinstead of.data:const machine = createMachine({ // ... states: { // ... success: { - data: { message: 'Success!' } + output: { message: 'Success!' } } } }) - Breaking
Support for getters as a transition target (instead of referencing state nodes by ID or relative key) has been removed.
The
Machine()andcreateMachine()factory functions no longer support passing incontextas a third argument.The
contextproperty in the machine configuration no longer accepts a function for determining context (which was introduced in 4.7). This might change as the API becomes finalized.The
activitiesproperty was removed fromStateobjects, as activities are now part ofinvokedeclarations.The state nodes will not show the machine's
versionon them - theversionproperty is only available on the root machine node. - Breaking
The
in: ...property for transitions is removed and replaced with guards. It is recommended to usestateIn()andnot(stateIn())guard creators instead:+ import { stateIn } from 'xstate/guards'; // ... on: { SOME_EVENT: { target: 'somewhere', - in: '#someState' + guard: stateIn('#someState') } } // ... - Breaking
Removed
Actor['status']from publicly available properties. - Breaking
All builtin action creators (
assign,sendTo, etc) are now returning functions. They exact shape of those is considered an implementation detail of XState and users are meant to only pass around the returned values. - Breaking
Autoforwarding events is no longer supported and the
autoForwardproperty has been removed.Instead of autoforwarding, events should be explicitly sent to actors:
invoke: { id: 'child', src: 'someSrc', - autoForward: true }, // ... on: { // ... + EVENT_TO_FORWARD: { + actions: sendTo('child', (_, event) => event) + } } - Breaking
The machine
.schemaproperty is now.types:const machine = createMachine({ // schema: { ... } types: {} as { context: { ... }; events: { ... }; // ... } });And the
.tsTypesproperty is now.types.typegen:const machine = createMachine({ // tsTypes: { ... } types: {} as { typegen: {}; context: { ... }; events: { ... }; // ... } }); - Breaking
Returning promises when creating a callback actor doesn't work anymore. Only cleanup functions can be returned now (or
undefined). - Breaking
There is now support for higher-level guards, which are guards that can compose other guards:
and([guard1, guard2, /* ... */])returnstrueif all guards evaluate to truthy, otherwisefalseor([guard1, guard2, /* ... */])returnstrueif any guard evaluates to truthy, otherwisefalsenot(guard1)returnstrueif a single guard evaluates tofalse, otherwisetrue
import { and, or, not } from 'xstate/guards'; const someMachine = createMachine({ // ... on: { EVENT: { target: 'somewhere', guard: and([ 'stringGuard', or([{ type: 'anotherGuard' }, not(() => false)]) ]) } } }); - Breaking
The
.send(...)method onactorRef.send(...)now requires the first argument (the event to send) to be an object; that is, either:an event object (e.g.
{ type: 'someEvent' })an SCXML event object.
The second argument (payload) is no longer supported, and should instead be included within the object:
-actorRef.send('SOME_EVENT') +actorRef.send({ type: 'SOME_EVENT' }) -actorRef.send('EVENT', { some: 'payload' }) +actorRef.send({ type: 'EVENT', some: 'payload' }) - Breaking
Actions and guards that follow eventless transitions will now receive the event that triggered the transition instead of a "null" event (
{ type: '' }), which no longer exists:// ... states: { a: { on: { SOME_EVENT: 'b' } }, b: { always: 'c' }, c: { entry: [({ event }) => { // event.type is now "SOME_EVENT", not "" }] } } // ... - Breaking
You can now add a
systemIdto spawned actors to reference them anywhere in the system.const machine = createMachine({ // ... context: ({ spawn }) => ({ actorRef: spawn( createMachine({ // ... }), { systemId: 'actorRef' } ) }) }); - Breaking
Reading the initial state from an actor via
actorRef.initialStateis removed. UseactorRef.getSnapshot()instead. - Breaking
machine.initialStatehas been removed, you can usemachine.getInitialState(...)instead - Breaking
Target resolution improvements: targeting sibling nodes from the root is no longer valid, since the root node has no siblings:
createMachine({ id: 'direction', initial: 'left', states: { left: {}, right: {} }, on: { - LEFT_CLICK: 'left', + LEFT_CLICK: '.left' } }); - Breaking
The
createActor(...)function now acceptsinputin the second argument, which passes input data in the"xstate.init"event:const greetMachine = createMachine({ context: ({ input }) => ({ greeting: `Hello ${input.name}!` }), entry: (_, event) => { event.type; // 'xstate.init' event.input; // { name: 'David' } } // ... }); const actor = createActor(greetMachine, { // Pass input data to the machine input: { name: 'David' } }).start(); - Breaking
Invoked actors can now be deeply persisted and restored. When the persisted state of an actor is obtained via
actorRef.getPersistedSnapshot(), the states of all invoked actors are also persisted, if possible. This state can be restored by passing the persisted state into thesnapshot: ...property of thecreateActoroptions argument:-createActor(machine).start(state); +createActor(machine, { snapshot }).start(); - Breaking
Atomic and parallel states should no longer be reentered when the transition target doesn't escape them. You can get the reentering behavior by configuring
reenter: truefor the transition. - Breaking
Restored state will no longer contain actions, since they are assumed to have already been executed. Actions will not be replayed.
If you want to replay actions when restoring state, it is recommended to use an event sourcing approach.
- Breaking
The
in: '...'transition property can now be replaced withstateIn(...)andstateNotIn(...)guards, imported fromxstate/guards:import { createMachine, + stateIn } from 'xstate/guards'; const machine = createMachine({ // ... on: { SOME_EVENT: { target: 'anotherState', - in: '#someState', + cond: stateIn('#someState') } } })The
stateIn(...)andstateNotIn(...)guards also can be used the same way assnapshot.matches(...):// ... SOME_EVENT: { target: 'anotherState', cond: stateNotIn({ red: 'stop' }) }An error will now be thrown if the
assign(...)action is executed when thecontextisundefined. Previously, there was only a warning.Error events raised by the machine will be thrown if there are no error listeners registered on an actor via
actorRef.subscribe({ error: () => {} }). - Breaking
Action/actor/delay/guard arguments are now consolidated into a single object argument. This is a breaking change for all of those things that are called with arguments.
assign({ - count: (context, event) => { + count: ({ context, event }) => { return context.count + event.value; } }) - Breaking
Eventless transitions must now be specified in the
always: { ... }object and not in theon: { ... }object:someState: { on: { // Will no longer work - '': { target: 'anotherState' } }, + always: { target: 'anotherState' } } - Breaking
Removed the ability to pass a string value directly to
invoke. To migrate you should use the object version ofinvoke:-invoke: 'myActor' +invoke: { src: 'myActor' } - Breaking
machine.transition(...)andmachine.getInitialState(...)require now anactorScopeargument - Breaking
All events automatically generated by XState will now be prefixed by
xstate.. Naming scheme changed slightly as well, for exampledone.invoke.*events becamexstate.done.actor.*events. - Breaking
The
escalate()action is removed. Just throw an error normally. - Breaking
The
actor.onTransition(...)method has been removed in favor of.subscribe(...)const actor = interpret(machine) - .onTransition(...) - .start(); +actor.subscribe(...); +actor.start();
- Breaking
Observing an actor via
actorRef.subscribe(...)no longer immediately receives the current snapshot. Instead, the current snapshot can be read fromactorRef.getSnapshot(), and observers will receive snapshots only when a transition in the actor occurs.const actorRef = createActor(machine); actorRef.start(); // Late subscription; will not receive the current snapshot actorRef.subscribe((state) => { // Only called when the actor transitions console.log(state); }); // Instead, current snapshot can be read at any time console.log(actorRef.getSnapshot()); - Breaking
Actors can no longer be stopped directly by calling
. They can only be stopped from its parent internally (which might happen when you useactor.stop()stopaction or automatically when a machine leaves the invoking state). The root actor can still be stopped since it has no parent. - Breaking
The
matchState(...)helper function is removed. - Breaking
Parameterized actions now require a
paramsproperty:// ... entry: [ { type: 'greet', - message: 'Hello' + params: { message: 'Hello' } } ] // ... - Breaking
The history resolution algorithm has been refactored to closely match the SCXML algorithm, which changes the shape of
state.historyValueto map history state node IDs to their most recently resolved target state nodes. - Breaking
Custom action objects and guard objects are now expected to put extra parameters on the
paramsproperty:actions: { type: 'sendMessage', - message: 'hello' + params: { + message: 'hello' + } } guard: { type: 'exists', - prop: 'user' + params: { + prop: 'user' + } } - Breaking
The
strict: trueoption for machine config has been removed. - Breaking
Removed the ability to define delayed transitions using an array. Only object variant is supported now:
createMachine({ initial: 'a', states: { a: { after: { 10000: 'b', noon: 'c' } } // ... } }); - Breaking
Removed
State['transitions']. - Breaking
Removed the deprecated
sendaction creator. Please usesendTowhen sending events to other actors orraisewhen sending to itself. - Breaking
The
createEmptyActor()function has been added to make it easier to create actors that do nothing ("empty" actors). This is useful for testing, or for some integrations such asuseActor(actor)in@xstate/reactthat require an actor:import { createEmptyActor } from 'xstate'; const SomeComponent = (props) => { // props.actor may be undefined const [state, send] = useActor(props.actor ?? createEmptyActor()); // ... }; - Breaking
machine.transitionno longer accepts state values. You have to resolve the state value to aStatebefore passing it tomachine.transition - Breaking
Removed
deferEventsfrom the actor options. - Breaking
The
state.historyproperty has been removed. This does not affect the machine "history" mechanism.Storing previous state should now be done explicitly:
let previousSnapshot; const actorRef = createActor(someMachine); actorRef.subscribe((snapshot) => { // previousSnapshot represents the last snapshot here // ... // update the previous snapshot at the end previousSnapshot = snapshot; }); actorRef.start(); - Breaking
All errors caught while executing the actor should now consistently include the error in its
snapshot.errorand should be reported to the closesterrorlistener. - Breaking
You can now import the following from
xstate:import { // actions // sendTo (removed) pure, // interpret helpers waitFor, // actor functions fromPromise, fromObservable, fromCallback, fromEventObservable, fromTransition, // guard functions stateIn, not, and, or }The
sendaction was removed from exports; usesendTo(...)orraise(...)instead. - Breaking
The
condproperty in transition config objects has been renamed toguard. This unifies terminology for guarded transitions and guard predicates (previously called "cond", or "conditional", predicates):someState: { on: { EVENT: { target: 'anotherState', - cond: 'isValid' + guard: 'isValid' } } } - Breaking
The
Machine()function has been removed. Use thecreateMachine()function instead.-import { Machine } from 'xstate'; +import { createMachine } from 'xstate'; -const machine = Machine({ +const machine = createMachine({ // ... }); - Breaking
The
interpreter.onError(...)method has been removed. Useinterpreter.subscribe({ error(err) => { ... } })instead. - Breaking
Actions are no longer called with
state - Breaking
spawnis no longer importable fromxstate. Instead you get it inassignlike this:assign((ctx, ev, { spawn }) => { return { ...ctx, actorRef: spawn(promiseActor) }; });In addition to that, you can now
spawnactors defined in your implementations object, in the same way that you were already able to do that withinvoke. To do that just reference the defined actor like this:spawn('promiseActor'); - Breaking
Stateclass has been removed and replaced byMachineSnapshotobject. They largely have the same properties and methods. On of the main noticeable results of this change is that you can no longer checkstate instanceof State. - Breaking
Guard arguments are now consolidated into a single object argument. This is a breaking change for all guards that are called with arguments.
- guard: (context, event) => { + guard: ({ context, event }) => { return context.count + event.value > 10; } - Breaking
The
service.batch(events)method is no longer available. - Breaking
The
StateSchematype has been removed from all generic type signatures. - Breaking
Removed
State['_internalQueue']. - Breaking
EmittedFromtype helper has been renamed toSnapshotFrom. - Breaking
The
fromReducer(...)function is now calledfromTransition(...). - Breaking
The
pure()andchoose()action creators have been removed, in favor of the more flexibleenqueueActions()action creator:entry: [ // pure(() => { // return [ // 'action1', // 'action2' // ] // }), enqueueActions(({ enqueue }) => { enqueue('action1'); enqueue('action2'); }) ];entry: [ // choose([ // { // guard: 'someGuard', // actions: ['action1', 'action2'] // } // ]), enqueueActions(({ enqueue, check }) => { if (check('someGuard')) { enqueue('action1'); enqueue('action2'); } }) ]; - Breaking
Changed behavior of
alwaystransitions. Previously they were always selected after selecting any transition (including thealwaystransitions). Because of that it was relatively easy to create an infinite loop using them.Now they are no longer selected if the preceeding transition doesn't change the state of a machine.
- Breaking
The
state.childrenproperty is now a mapping of invoked actor IDs to theirActorRefinstances.Breaking: The way that you interface with invoked/spawned actors is now through
ActorRefinstances. AnActorRefis an opaque reference to anActor, which should be never referenced directly.Breaking: The
originof anSCXML.Eventis no longer a string, but anActorRefinstance. - Breaking
The
servicesoption passed as the second argument tocreateMachine(config, options)is renamed toactors. Each value inactorsshould be a function that takes incontextandeventand returns a [behavior](TODO: link) for an actor. The provided behavior creators are:fromMachinefromPromisefromCallbackfromObservablefromEventObservable
import { createMachine } from 'xstate'; +import { fromPromise } from 'xstate/actors'; const machine = createMachine( { // ... invoke: { src: 'fetchFromAPI' } }, { - services: { + actors: { - fetchFromAPI: (context, event) => { + fetchFromAPI: (context, event) => fromPromise(() => { // ... (return a promise) }) } } ); - Breaking
The error event (
type: 'xstate.error.*') now has the error data on theevent.errorinstead ofevent.data:// ... invoke: { src: 'someSrc', onError: { actions: ({ event }) => { - event.data; + event.error; } } } - Breaking
_eventhas been removed from all APIs and types. It was a wrapper structure containing theeventthat users were using directly. - Breaking
Actor types can now be specified in the
.typesproperty ofcreateMachine:const fetcher = fromPromise(() => fetchUser()); const machine = createMachine({ types: {} as { actors: { src: 'fetchData'; // src name (inline behaviors ideally inferred) id: 'fetch1' | 'fetch2'; // possible ids (optional) logic: typeof fetcher; }; }, invoke: { src: 'fetchData', // strongly typed id: 'fetch2', // strongly typed onDone: { actions: ({ event }) => { event.output; // strongly typed as { result: string } } }, input: { foo: 'hello' } // strongly typed } }); - Breaking
Interpreter['off']method has been removed. - Breaking
.nextStatemethod has been removed from theInterpreter.State#cancan be used to check if sending a particular event would lead to a state change. - Breaking
Support for compound string state values has been dropped from Machine's transition method. It's no longer allowed to call transition like this -
machine.transition('a.b', { type: 'NEXT' }), instead it's required to use "state value" representation like this -machine.transition({ a: 'b' }, { type: 'NEXT' }). - Breaking
Activities removed (can be invoked)
Since activities can be considered invoked services, they can be implemented as such. Activities are services that do not send any events back to the parent machine, nor do they receive any events, other than a "stop" signal when the parent changes to a state where the activity is no longer active. This is modeled the same way as a callback service is modeled.
- Breaking
Removed previously deprecated config properties:
onEntry,onExit,parallelandforward. - Breaking
The
state._sessionidproperty has been removed. It should be obtained directly from the actor:actor.sessionId. - Breaking
The
systemcan now be accessed in all available actor logic creator functions:fromPromise(({ system }) => { ... }); fromTransition((state, event, { system }) => { ... }); fromObservable(({ system }) => { ... }); fromEventObservable(({ system }) => { ... }); fromCallback((sendBack, receive, { system }) => { ... }); - Breaking
Typings for
Typestatehave been removed. The reason for this is that types for typestates needed to be manually specified, which is unsound because it is possible to specify impossible typestates; i.e., typings for a state'svalueandcontextthat are impossible to achieve. - Breaking
The
actor.onDone(...)method is removed. Useactor.subscribe({ complete() {... } })instead.- actor.onDone(() => { ... }) + actor.subscribe({ + complete() { + // ... + } +}) - Breaking
The
createModel()function has been removed in favor of relying on strong types in the machine configuration. - Breaking
syncoption has been removed frominvokeandspawn. - Breaking
Removed
State['event']. - Breaking
The final
outputof a state machine is now specified directly in theoutputproperty of the machine config:const machine = createMachine({ initial: 'started', states: { started: { // ... }, finished: { type: 'final' // moved to the top level // // output: { // status: 200 // } } }, // This will be the final output of the machine // present on `snapshot.output` and in the done events received by the parent // when the machine reaches the top-level final state ("finished") output: { status: 200 } }); - Breaking
Invoked/spawned actors are no longer available on
service.children- they can only be accessed fromstate.children. - Breaking
Removed
mapStateutility function. - Breaking
The
interpret(...)function has been deprecated and renamed tocreateActor(...):-import { interpret } from 'xstate'; +import { createActor } from 'xstate'; -const actor = interpret(machine); +const actor = createActor(machine); - Breaking
Prefix wildcard event descriptors are now supported. These are event descriptors ending with
".*"which will match all events that start with the prefix (the partial event type before".*"):// ... on: { 'mouse.click': {/* ... */}, // Matches events such as: // "pointer.move" // "pointer.move.out" // "pointer" 'pointer.*': {/* ... */} } // ...Note: wildcards are only valid as the entire event type (
"*") or at the end of an event type, preceded by a period (".*"):✅
"*"✅
"event.*"✅
"event.something.*"❌
"event.*.something"❌
"event*"❌
"event*.some*thing"❌
"*.something"
- Breaking
The interface for guard objects has changed. Notably, all guard parameters should be placed in the
paramsproperty of the guard object:Example taken from Custom Guards:
-cond: { +guard: { - name: 'searchValid', // `name` property no longer used type: 'searchValid', - minQueryLength: 3 + params: { + minQueryLength: 3 + } } - Breaking
All transitions became internal by default. The style of the
targetpattern (.child,sibling,#id) has now no effect on the transition type.Internal transitions don't reenter their source state when the target lies within it. You can still create external transitions (ones that reenter the source state under the mentioned circumstances) by explicitly setting
external: trueon the given transition. - Breaking
exitactions of all states are no longer called when the machine gets stopped externally. Note that they are still called when the machine reaches its final state. - Breaking
Machine#transitionno longer handles invalid state values such as values containing non-existent state regions. If you rehydrate your machines and change machine's schema then you should migrate your data accordingly on your own. - Breaking
Removed support for
service.send(type, payload). We are usingsendAPI at multiple places and this was the only one supporting this shape of parameters. Additionally, it had not strict TS types and using it was unsafe (type-wise). - Breaking
Spawned actors that have a referenced source (not inline) can be deeply persisted and restored:
const machine = createMachine({ context: ({ spawn }) => ({ // This will be persisted ref: spawn('reducer', { id: 'child' }) // This cannot be persisted: // ref: spawn(fromTransition((s) => s, { count: 42 }), { id: 'child' }) }) }).provide({ actors: { reducer: fromTransition((s) => s, { count: 42 }) } }); - Breaking
Removed
State['actions']. Actions are considered to be a side-effect of a transition, things that happen in the moment and are not meant to be persisted beyond that.
Minor Changes
exportsfield has been added to thepackage.jsonmanifest. It limits what files can be imported from a package - it's no longer possible to import from files that are not considered to be a part of the public API.Merge
sendBackandreceivewith other properties offromCallbacklogic creator.const callbackLogic = fromCallback(({ input, system, self, sendBack, receive }) => { ... });The
stateoption ofcreateActor(...)has been renamed tosnapshot:createActor(machine, { - state: someState + snapshot: someState })Likewise, the
.getPersistedState()method has been renamed to.getPersistedSnapshot():-actor.getPersistedState() +actor.getPersistedSnapshot()
spawncan now benefit from the actor types. Its arguments are strongly-typed based on them.Significant improvements to error handling have been made:
Actors will no longer crash when an error is thrown in an observer (
actor.subscribe(observer)).Errors will be handled by observer's
.error()handler:actor.subscribe({ error: (error) => { // handle error } });If an observer does not have an error handler, the error will be thrown in a clear stack so bug tracking services can collect it.
You can now
spawnChild(...)actors directly outside ofassign(...)action creators:import { createMachine, spawnChild } from 'xstate'; const listenerMachine = createMachine({ // ... }); const parentMachine = createMachine({ // ... on: { 'listener.create': { entry: spawnChild(listenerMachine, { id: 'listener' }) } } // ... }); const actor = createActor(parentMachine).start(); actor.send({ type: 'listener.create' }); actor.getSnapshot().children.listener; // ActorRefFrom<typeof listenerMachine>onSnapshotis now available for invoke configs. You can specify a transition there to be taken when a snapshot of an invoked actor gets updated. It works similarly toonDone/onError.Partial event descriptors are now type-safe:
createMachine({ types: {} as { events: | { type: 'mouse.click.up'; direction: 'up' } | { type: 'mouse.click.down'; direction: 'down' } | { type: 'mouse.move' } | { type: 'keypress' }; }, on: { 'mouse.click.*': { actions: ({ event }) => { event.type; // 'mouse.click.up' | 'mouse.click.down' event.direction; // 'up' | 'down' } }, 'mouse.*': { actions: ({ event }) => { event.type; // 'mouse.click.up' | 'mouse.click.down' | 'mouse.move' } } } });State.from,StateMachine#createStateandStateMachine#resolveStateValuewere removed. They largely served the same purpose asStateMachine#resolveStateand this is the method that is still available and can be used instead of them.Params of
actionsandguardscan now be resolved dynamicallycreateMachine({ types: {} as { actions: | { type: 'greet'; params: { surname: string } } | { type: 'poke' }; }, entry: { type: 'greet', params: ({ context }) => ({ surname: 'Doe' }) } });Children IDs in combination with
setupcan now be typed usingtypes.children:const machine = setup({ types: {} as { children: { myId: 'actorKey'; }; }, actors: { actorKey: child } }).createMachine({}); const actorRef = createActor(machine).start(); actorRef.getSnapshot().children.myId; // ActorRefFrom<typeof child> | undefinedYou can now specify guard types for machines:
createMachine({ types: {} as { guards: | { type: 'isGreaterThan'; params: { count: number; }; } | { type: 'plainGuard' }; } // ... });You can now define strict tags for machines:
createMachine({ types: {} as { tags: 'pending' | 'success' | 'error'; } // ... });The
state.configurationproperty has been renamed tostate.nodes.- state.configuration + state.nodes
The
onSnapshot: { ... }transition object is now supported for invoked machines, observables, promises, and transition functions:const machine = createMachine({ // ... invoke: [ { src: createMachine({ ... }), onSnapshot: { actions: (context, event) => { event.snapshot; // machine state } } }, { src: fromObservable(() => ...), onSnapshot: { actions: (context, event) => { event.snapshot; // observable value } } }, { src: fromTransition((state, event) => { ... }, /* ... */), onSnapshot: { actions: (context, event) => { event.snapshot; // transition function return value } } } ] });The
stop(...)action creator is renamed tostopChild(...), to make it clear that only child actors may be stopped from the parent actor.Action parameters can now be directly accessed from the 2nd argument of the action implementation:
const machine = createMachine( { // ... entry: { type: 'greet', params: { message: 'hello' } } }, { actions: { greet: (_, params) => { params.message; // 'hello' } } } );Input types can now be specified for machines:
const emailMachine = createMachine({ types: {} as { input: { subject: string; message: string; }; }, context: ({ input }) => ({ // Strongly-typed input! emailSubject: input.subject, emailBody: input.message.trim() }) }); const emailActor = interpret(emailMachine, { input: { // Strongly-typed input! subject: 'Hello, world!', message: 'This is a test.' } }).start();xstate.done.state.*events will now be generated recursively for all parallel states on the ancestors path.Actor logic creators now have access to
self:const promiseLogic = fromPromise(({ self }) => { ... }); const observableLogic = fromObservable(({ self }) => { ... }); const callbackLogic = fromCallback((sendBack, receive, { self }) => { ... }); const transitionLogic = fromTransition((state, event, { self }) => { ... }, ...);Guard parameters can now be directly accessed from the 2nd argument of the guard implementation:
const machine = createMachine( { // ... on: { EVENT: { guard: { type: 'isGreaterThan', params: { value: 10 } } } } }, { guards: { isGreaterThan: (_, params) => { params.value; // 10 } } } );You can now inspect actor system updates using the
inspectoption increateActor(logic, { inspect }). The types of inspection events you can observe 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 event
import { createMachine } from 'xstate'; const machine = createMachine({ // ... }); const actor = createActor(machine, { inspect: (inspectionEvent) => { if (inspectionEvent.type === '@xstate.actor') { console.log(inspectionEvent.actorRef); } if (inspectionEvent.type === '@xstate.event') { console.log(inspectionEvent.sourceRef); console.log(inspectionEvent.targetRef); console.log(inspectionEvent.event); } if (inspectionEvent.type === '@xstate.snapshot') { console.log(inspectionEvent.actorRef); console.log(inspectionEvent.event); console.log(inspectionEvent.snapshot); } } });Added support for expressions to
cancelaction.The new
enqueueActions(...)action creator can now be used to enqueue actions to be executed. This is a helpful alternative to thepure(...)andchoose(...)action creators.const machine = createMachine({ // ... entry: enqueueActions(({ context, event, enqueue, check }) => { // assign action enqueue.assign({ count: context.count + 1 }); // Conditional actions (replaces choose(...)) if (event.someOption) { enqueue.sendTo('someActor', { type: 'blah', thing: context.thing }); // other actions enqueue('namedAction'); // with params enqueue({ type: 'greet', params: { message: 'hello' } }); } else { // inline enqueue(() => console.log('hello')); // even built-in actions } // Use check(...) to conditionally enqueue actions based on a guard if (check({ type: 'someGuard' })) { // ... } // no return }) });The default
timeoutforwaitFor(...)is nowInfinityinstead of 10 seconds.You can now specify action types for machines:
createMachine({ types: {} as { actions: { type: 'greet'; params: { name: string } }; }, entry: [ { type: 'greet', params: { name: 'David' } }, // @ts-expect-error { type: 'greet' }, // @ts-expect-error { type: 'unknownAction' } ] // ... });The
state.metagetter has been replaced withstate.getMeta()methods:- state.meta + state.getMeta()
Output types can now be specified in the machine:
const machine = createMachine({ types: {} as { output: { result: 'pass' | 'fail'; score: number; }; } // ... }); const actor = createActor(machine); // ... const snapshot = actor.getSnapshot(); if (snapshot.output) { snapshot.output.result; // strongly typed as 'pass' | 'fail' snapshot.output.score; // strongly typed as number }Added interop observable symbols to
ActorRefso that actor refs are compatible with libraries like RxJS.You can now use the
setup({ ... }).createMachine({ ... })function to setup implementations foractors,actions,guards, anddelaysthat will be used in the created machine:import { setup, createMachine } from 'xstate'; const fetchUser = fromPromise(async ({ input }) => { const response = await fetch(`/user/${input.id}`); const user = await response.json(); return user; }); const machine = setup({ actors: { fetchUser }, actions: { clearUser: assign({ user: undefined }) }, guards: { isUserAdmin: (_, params) => params.user.role === 'admin' } }).createMachine({ // ... invoke: { // Strongly typed! src: 'fetchUser', input: ({ context }) => ({ id: context.userId }), onDone: { guard: { type: 'isUserAdmin', params: ({ context }) => ({ user: context.user }) }, target: 'success', actions: assign({ user: ({ event }) => event.output }) }, onError: { target: 'failure', actions: 'clearUser' } } });You can now specify delay types for machines:
createMachine({ types: {} as { delays: 'one second' | 'one minute'; } // ... });The event type of internal
afterevents changed fromxstate.after(1000)#some.state.idtoxstate.after.1000.some.state.idfor consistency.Pr
author: @Andarist
author: @davidkpianoState values and
snapshot.matches()argument are now strongly-typed when using thesetupAPI.
Patch Changes
The
machine.optionsproperty has been renamed tomachine.implementationsFixed an issue with inline actions not being correctly executed when there was an equally named action provided through the
implementationsargument.Fixed a runtime crash related to machines with their root state's type being final (
createMachine({ type: 'final' })).Added support to
stateInguard for checking a combination of an ID and a path, eg.stateIn('#b.B1').Remove
State['changed']. A new instance ofStateis being created if there are matching transitions for the received event. If there are no matching transitions then the current state is being returned.Removed the ability to configure transitions using arrays:
createMachine({ on: [{ event: 'FOO', target: '#id' }] // ... });Only regular object-based configs will be supported from now on:
createMachine({ on: { FOO: '#id' } // ... });Fixed an issue with actors not being reinstantiated correctly when an actor with the same ID was first stopped and then invoked/spawned again in the same microstep.
- 4.x
4.38.3
23 Oct 2023Reading the note…
4.38.2
27 Jul 2023Reading the note…
4.38.1
12 Jul 2023Reading the note…
4.38.0
25 Jun 2023The
log,pure,choose, andstopactions were added to the main export:import { log, pure, choose, stop } from 'xstate';
4.37.2
26 Apr 2023Reading the note…
4.37.1
23 Mar 2023Reading the note…
4.37.0
24 Feb 2023The new
TagsFromhelper type extracts the type oftagsfrom a state machine when typegen is enabled:const machine = createMachine({ // `tags` attached to machine via typegen tsTypes: {} as import('./machine.typegen').Typegen0, tags: ['a', 'b'], states: { idle: { tags: 'c' } } }); type Tags = TagsFrom<typeof machine>; // 'a' | 'b' | 'c'If typegen is not enabled,
TagsFromreturnsstring:const machine = createMachine({ tags: ['a', 'b'], states: { idle: { tags: 'c' } } }); type Tags = TagsFrom<typeof machine>; // stringFixed event type narrowing in some of the builtin actions.
4.36.0
13 Feb 2023- Deprecated
Deprecated
send()action creator. Instead of that, you can usesendTo()to send events to other actors andraise()to send events to the "self" actor. Fixed a class of inference problems for our builtin actions (
assign,sendTo, etc).All actions received a new generic:
TExpressionEvent. To type things more correctly and allow TS to infer things better we need to distinguish between all events accepted by a machine (TEvent) and the event type that actions are "called" with (TExpressionEvent).It's best to rely on type inference so you shouldn't have to specify this generic manually all over the place.
Minor Changes
- Deprecated
Deprecated
send()action creator. Instead of that, you can usesendTo()to send events to other actors andraise()to send events to the "self" actor. Fixed a class of inference problems for our builtin actions (
assign,sendTo, etc).All actions received a new generic:
TExpressionEvent. To type things more correctly and allow TS to infer things better we need to distinguish between all events accepted by a machine (TEvent) and the event type that actions are "called" with (TExpressionEvent).It's best to rely on type inference so you shouldn't have to specify this generic manually all over the place.
Patch Changes
Fixed inference for
assignusingPropertyAssigner, like here:actions: assign({ counter: 0, delta: (ctx, ev) => ev.delta });
4.35.4
30 Jan 2023Reading the note…
4.35.3
28 Jan 2023Reading the note…
4.35.2
5 Jan 2023Reading the note…
4.35.1
19 Dec 2022Reading the note…
4.35.0
5 Dec 2022The
createModel(...)function is now marked as deprecated, as it will be removed in XState version 5. It is recommended to use Typegen instead.Fixed an issue with targeted ancestors not being correctly exited when reented during external transitions.
Fixed an issue with external transitions targeting ancestor states. In such a case,
entryactions were incorrectly called on the states between the source state and the target state for states that were not reentered within this transition.
Minor Changes
The
createModel(...)function is now marked as deprecated, as it will be removed in XState version 5. It is recommended to use Typegen instead.
Patch Changes
Fixed an issue with targeted ancestors not being correctly exited when reented during external transitions.
Fixed an issue with external transitions targeting ancestor states. In such a case,
entryactions were incorrectly called on the states between the source state and the target state for states that were not reentered within this transition.Fixed an issue with the active descendants of the targeted ancestor not being correctly reentered during external transitions.
Updated
pureaction types to allow actiontypestrings to be returned in the array.const machine = createMachine( { entry: ['doStuff'] }, { actions: { doStuff: pure(() => ['someAction']), someAction: () => console.log('executed by doStuff') } } );Returning action
typestrings were already handled byxstateand the types now correctly reflect that.The warning for the
predictableActionArgumentssetting has been improved to only warn if it is absent. You can disable the warning by settingpredictableActionArguments: false. It's still recommended to set it totruethough.
4.34.0
29 Oct 2022The actions
raiseandsendTocan now be imported directly fromxstate:import { raise, sendTo } from 'xstate'; // ...Fixed a regression that has caused
machine.getInitialState(value)to not follow always transitions correctly.
4.33.6
9 Sep 2022Reading the note…
4.33.5
1 Sep 2022Reading the note…
4.33.4
26 Aug 2022Reading the note…
4.33.3
23 Aug 2022Reading the note…
4.33.2
15 Aug 2022Reading the note…
4.33.1
11 Aug 2022Reading the note…
4.33.0
5 Aug 2022A new
predictableActionArgumentsfeature flag has been added that allows you to opt into some fixed behaviors that will be the default in v5. With this flag:Please be aware that you might not able to use
statefrom themetaargument when using this flag.All
exitactions in the machine will now be correctly resolved and executed when a machine gets stopped or reaches its top-level final state. Previously, the actions were not correctly resolved and that was leading to runtime errors.To implement this fix in a reliable way, a new internal event has been introduced:
{ type: 'xstate.stop' }and when the machine stops its execution, all exit handlers of the current state (i.e. the active state nodes) will be called with that event. You should always assume that an exit handler might be called with that event.Added a dev-only error when
forwardToaccidentally ends up trying to forward an event to an undefined actor. Such a situation indicates a logical error and risks an infinite loop.
Minor Changes
A new
predictableActionArgumentsfeature flag has been added that allows you to opt into some fixed behaviors that will be the default in v5. With this flag:XState will always call an action with the event directly responsible for the related transition,
you also automatically opt-into
preserveActionOrder.
Please be aware that you might not able to use
statefrom themetaargument when using this flag.All
exitactions in the machine will now be correctly resolved and executed when a machine gets stopped or reaches its top-level final state. Previously, the actions were not correctly resolved and that was leading to runtime errors.To implement this fix in a reliable way, a new internal event has been introduced:
{ type: 'xstate.stop' }and when the machine stops its execution, all exit handlers of the current state (i.e. the active state nodes) will be called with that event. You should always assume that an exit handler might be called with that event.
Patch Changes
Added a dev-only error when
forwardToaccidentally ends up trying to forward an event to an undefined actor. Such a situation indicates a logical error and risks an infinite loop.Call the
completecallback of the subscribedobserverwhen an interpreter gets stopped.Fixed an issue with parallel regions not always being correctly reentered on external transitions of the containing parallel state targeting another region within that parallel state.
The types for
state.nextEventsare now properly typed to the actual event types of the machine. Original PR: #1115 (Thanks @alexreardon!)Fixed an issue with targeted ancestors not being correctly reentered during external transitions.
4.32.1
13 May 2022Reading the note…
4.32.0
6 May 2022Added a
StateValueFromhelper that can be used to extract valid state values from a machine. This might specifically be useful with typegen because typegenlessstate.matchesacceptsanyanyway.Removing the timeout that's built in to
waitForis now supported by explicitly passing anInfinityvalue.Example usage:
import { waitFor } from 'xstate/lib/waitFor'; // This will const loggedInState = await waitFor( loginService, state => state.hasTag('loggedIn'), { timeout: Infinity } );This fixes a bug that causes
waitForto reject with an error immediately due to the behaviour ofsetTimeout.Fixed an issue with typegen types not being able to provide events that had a union of strings as their
type(such as{ type: 'INC' | 'DEC'; value: number; }).
Minor Changes
Added a
StateValueFromhelper that can be used to extract valid state values from a machine. This might specifically be useful with typegen because typegenlessstate.matchesacceptsanyanyway.
Patch Changes
Removing the timeout that's built in to
waitForis now supported by explicitly passing anInfinityvalue.Example usage:
import { waitFor } from 'xstate/lib/waitFor'; // This will const loggedInState = await waitFor( loginService, state => state.hasTag('loggedIn'), { timeout: Infinity } );This fixes a bug that causes
waitForto reject with an error immediately due to the behaviour ofsetTimeout.Fixed an issue with typegen types not being able to provide events that had a union of strings as their
type(such as{ type: 'INC' | 'DEC'; value: number; }).Fixed an issue with
EventFromnot being able to extract events that had a union of strings as theirtype(such as{ type: 'INC' | 'DEC'; value: number; }).Fixed an issue with action objects not receiving correct event types when used in the second argument to the
createMachine.The typings for
sendTo(...)have been fixed.Fixed an issue with inline functions in the config object used as transition actions not having their argument types inferred.
Fixed an issue with default
TEvent({ type: string }) not being correctly provided to inline transition actions.
4.31.0
8 Apr 2022The
waitFor(...)helper function, which asynchronously waits for an actor's emitted value to satisfy apredicatebefore atimeout, is now available.Example usage:
import { waitFor } from 'xstate/lib/waitFor'; // ... const loginService = interpret(loginMachine).start(); const loggedInState = await waitFor(loginService, state => state.hasTag('loggedIn') ); loggedInState.hasTag('loggedIn'); // trueSubscribing to a stopped interpreter will now always immediately emit its state and call a completion callback.
Fixed an issue with
state.tagsnot having correct values when resolving micro transitions (taken in response to raised events). This was creating issues when checking tags in guards.
Minor Changes
The
waitFor(...)helper function, which asynchronously waits for an actor's emitted value to satisfy apredicatebefore atimeout, is now available.Example usage:
import { waitFor } from 'xstate/lib/waitFor'; // ... const loginService = interpret(loginMachine).start(); const loggedInState = await waitFor(loginService, state => state.hasTag('loggedIn') ); loggedInState.hasTag('loggedIn'); // trueSubscribing to a stopped interpreter will now always immediately emit its state and call a completion callback.
Patch Changes
Fixed an issue with
state.tagsnot having correct values when resolving micro transitions (taken in response to raised events). This was creating issues when checking tags in guards.Fixed an issue with
onDoneon parallel states not being "called" correctly when a parallel state had a history state defined directly on it.Fixed issues with not disposing some cached internal values when stopping interpreters, which could have led to issues when starting such an interpreter again.
Made type displays (like in the IDE tooltips etc) more readable by using a type interface for the internal
ResolveTypegenMetatype.
4.30.6
11 Mar 2022Reading the note…
4.30.5
4 Mar 2022Reading the note…
A whole project to check? Paste its package.json in the dependency check: every deprecated, outdated or vulnerable dependency, with what to upgrade to. Free, no account.