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.
4.30.4
4 Mar 2022Reading the note…
4.30.3
1 Mar 2022Reading the note…
4.30.2
22 Feb 2022Reading the note…
4.30.1
15 Feb 2022Reading the note…
4.30.0
12 Feb 2022- Deprecated
Marked all phantom properties on the
StateMachinetype as deprecated. This deprioritized them in IDEs so they don't popup as first suggestions during property access. All actions are now available in the
actionsvariable when importing:import { actions } from 'xstate'Persisted state can now be easily restored to a state compatible with the machine without converting it to a
Stateinstance first:// Persisting a state someService.subscribe(state => { localStorage.setItem('some-state', JSON.stringify(state)); }); // Restoring a state const stateJson = localStorage.getItem('some-state'); // No need to convert `stateJson` object to a state! const someService = interpret(someMachine).start(stateJson);
Minor Changes
All actions are now available in the
actionsvariable when importing:import { actions } from 'xstate'Persisted state can now be easily restored to a state compatible with the machine without converting it to a
Stateinstance first:// Persisting a state someService.subscribe(state => { localStorage.setItem('some-state', JSON.stringify(state)); }); // Restoring a state const stateJson = localStorage.getItem('some-state'); // No need to convert `stateJson` object to a state! const someService = interpret(someMachine).start(stateJson);
Patch Changes
Fixed an issue with a reference to
@types/nodebeing inserted into XState's compiled output. This could cause unexpected issues in projects expecting APIs likesetTimeoutto be typed with browser compatibility in mind.Fixed an issue with states created using
machine.getInitialStatenot being "resolved" in full. This could cause some things, such asaftertransitions, not being executed correctly after starting an interpreter using such state.- Deprecated
Marked all phantom properties on the
StateMachinetype as deprecated. This deprioritized them in IDEs so they don't popup as first suggestions during property access. Fixed an issue with
state.contextbecominganyafterstate.matcheswhen typegen is used.Moved an internal
@ts-ignoreto a JSDoc-style comment to fix consuming projects that do not useskipLibCheck. Regular inline and block comments are not preserved in the TypeScript's emit.
4.29.0
27 Jan 2022Using
config.schemabecomes the preferred way of "declaring" TypeScript generics with this release:createMachine({ schema: { context: {} as { count: number }, events: {} as { type: 'INC' } | { type: 'DEC' } } })This allows us to leverage the inference algorithm better and unlocks some exciting possibilities for using XState in a more type-strict manner.
Added the ability to tighten TS declarations of machine with generated metadata. This opens several exciting doors to being able to use typegen seamlessly with XState to provide an amazing typing experience.
With the VS Code extension, you can specify a new attribute called
tsTypes: {}in your machine definition:const machine = createMachine({ tsTypes: {} });The extension will automatically add a type assertion to this property, which allows for type-safe access to a lot of XState's API's.
⚠️ This feature is in beta. Actions/services/guards/delays might currently get incorrectly annotated if they are called "in response" to always transitions or raised events. We are working on fixing this, both in XState and in the typegen.
Added
t(), which can be used to provide types forschemaattributes in machine configs:import { t, createMachine } from 'xstate'; const machine = createMachine({ schema: { context: t<{ value: number }>(), events: t<{ type: 'EVENT_1' } | { type: 'EVENT_2' }>() } });
Minor Changes
Using
config.schemabecomes the preferred way of "declaring" TypeScript generics with this release:createMachine({ schema: { context: {} as { count: number }, events: {} as { type: 'INC' } | { type: 'DEC' } } })This allows us to leverage the inference algorithm better and unlocks some exciting possibilities for using XState in a more type-strict manner.
Added the ability to tighten TS declarations of machine with generated metadata. This opens several exciting doors to being able to use typegen seamlessly with XState to provide an amazing typing experience.
With the VS Code extension, you can specify a new attribute called
tsTypes: {}in your machine definition:const machine = createMachine({ tsTypes: {} });The extension will automatically add a type assertion to this property, which allows for type-safe access to a lot of XState's API's.
⚠️ This feature is in beta. Actions/services/guards/delays might currently get incorrectly annotated if they are called "in response" to always transitions or raised events. We are working on fixing this, both in XState and in the typegen.
Patch Changes
Added
t(), which can be used to provide types forschemaattributes in machine configs:import { t, createMachine } from 'xstate'; const machine = createMachine({ schema: { context: t<{ value: number }>(), events: t<{ type: 'EVENT_1' } | { type: 'EVENT_2' }>() } });The repository links have been updated from
github.com/davidkpianotogithub.com/statelyai.
4.28.1
21 Jan 2022Reading the note…
4.28.0
18 Jan 2022Added interop observable symbols to
ActorRefso that actor refs are compatible with libraries like RxJS.Generated IDs for invocations that do not provide an
idare now based on the state ID to avoid collisions:createMachine({ id: 'test', initial: 'p', states: { p: { type: 'parallel', states: { // Before this change, both invoke IDs would be 'someSource', // which is incorrect. a: { invoke: { src: 'someSource' // generated invoke ID: 'test.p.a:invocation[0]' } }, b: { invoke: { src: 'someSource' // generated invoke ID: 'test.p.b:invocation[0]' } } } } } });The
sendTo(actorRef, event)action creator introduced in4.27.0, which was not accessible from the package exports, can now be used just like other actions:import { actions } from 'xstate'; const { sendTo } = actions;
4.27.0
30 Dec 2021The
sendTo(actorRef, event)action creator has been introduced. It allows you to specify the recipient actor ref of an event first, so that the event can be strongly typed against the events allowed to be received by the actor ref:// ... entry: sendTo( (ctx) => ctx.someActorRef, { type: 'EVENT_FOR_ACTOR' } ), // ...The
state.can(...)method no longer unnecessarily executesassign()actions and instead determines if a given event will change the state by reading transition data before evaluating actions.Fixed an issue with stopped children sometimes starting their own child actors. This could happen when the child was stopped synchronously (for example by its parent) when transitioning to an invoking state.
Minor Changes
The
sendTo(actorRef, event)action creator has been introduced. It allows you to specify the recipient actor ref of an event first, so that the event can be strongly typed against the events allowed to be received by the actor ref:// ... entry: sendTo( (ctx) => ctx.someActorRef, { type: 'EVENT_FOR_ACTOR' } ), // ...
Patch Changes
The
state.can(...)method no longer unnecessarily executesassign()actions and instead determines if a given event will change the state by reading transition data before evaluating actions.Fixed an issue with stopped children sometimes starting their own child actors. This could happen when the child was stopped synchronously (for example by its parent) when transitioning to an invoking state.
Fixed an issue with some exit handlers being executed more than once when stopping a machine.
4.26.1
22 Nov 2021Reading the note…
4.26.0
1 Nov 2021The
descriptionproperty is a new top-level property for state nodes and transitions, that lets you provide text descriptions:const machine = createMachine({ // ... states: { active: { // ... description: 'The task is in progress', on: { DEACTIVATE: { // ... description: 'Deactivates the task' } } } } });Future Stately tooling will use the
descriptionto render automatically generated documentation, type hints, and enhancements to visual tools.Add optional type parameter to narrow type returned by
EventFrom. You can use it like this:type UpdateNameEvent = EventFrom<typeof userModel>;
The
tagsproperty was missing from state's definitions. This is used when converting a state to a JSON string. Since this is how we serialize states within@xstate/inspectthis has caused inspected machines to miss thetagsinformation.
Minor Changes
The
descriptionproperty is a new top-level property for state nodes and transitions, that lets you provide text descriptions:const machine = createMachine({ // ... states: { active: { // ... description: 'The task is in progress', on: { DEACTIVATE: { // ... description: 'Deactivates the task' } } } } });Future Stately tooling will use the
descriptionto render automatically generated documentation, type hints, and enhancements to visual tools.Add optional type parameter to narrow type returned by
EventFrom. You can use it like this:type UpdateNameEvent = EventFrom<typeof userModel>;
Patch Changes
The
tagsproperty was missing from state's definitions. This is used when converting a state to a JSON string. Since this is how we serialize states within@xstate/inspectthis has caused inspected machines to miss thetagsinformation.Fixed an issue with tags being missed on a service state after starting that service using a state value, like this:
const service = interpret(machine).start('active'); service.state.hasTag('foo'); // this should now return a correct resultMeta data can now be specified for
invokeconfigs in theinvoke.metaproperty:const machine = createMachine({ // ... invoke: { src: (ctx, e) => findUser(ctx.userId), meta: { summary: 'Finds user', updatedAt: '2021-09-...', version: '4.12.2' // other descriptive meta properties } } });
4.25.0
16 Sep 2021Removed the ability to pass a model as a generic to
createMachine, in favour ofmodel.createMachine. This lets us cut an overload from the definition ofcreateMachine, meaning errors become more targeted and less cryptic.This means that this approach is no longer supported:
const model = createModel({}); const machine = createMachine<typeof model>();If you're using this approach, you should use
model.createMachineinstead:const model = createModel({}); const machine = model.createMachine();Fixed a regression in the inline actions type inference in models without explicit action creators.
const model = createModel( { foo: 100 }, { events: { BAR: () => ({}) } } ); model.createMachine({ // `ctx` was of type `any` entry: ctx => {}, exit: assign({ // `ctx` was of type `unknown` foo: ctx => 42 }) });
4.24.1
15 Sep 2021Reading the note…
4.24.0
14 Sep 2021You can now know if an event will cause a state change by using the new
state.can(event)method, which will returntrueif an interpreted machine will "change" the state when sent theevent, orfalseotherwise:const machine = createMachine({ initial: 'inactive', states: { inactive: { on: { TOGGLE: 'active' } }, active: { on: { DO_SOMETHING: { actions: ['something'] } } } } }); const state = machine.initialState; state.can('TOGGLE'); // true state.can('DO_SOMETHING'); // false // Also takes in full event objects: state.can({ type: 'DO_SOMETHING', data: 42 }); // falseA state is considered "changed" if any of the following are true:
See
state.changed(documentation) for more details.A regression was fixed where actions were being typed as
neverif events were specified increateModel(...)but not actions:const model = createModel( {}, { events: {} } ); model.createMachine({ // These actions will cause TS to not compile entry: 'someAction', exit: { type: 'someObjectAction' } });
4.23.4
3 Sep 2021Reading the note…
4.23.3
31 Aug 2021Reading the note…
4.23.2
30 Aug 2021Reading the note…
4.23.1
24 Jul 2021Reading the note…
4.23.0
16 Jul 2021There is a new
.preserveActionOrder(default:false) setting in the machine configuration that preserves the order of actions when set totrue. Normally, actions are executed in order except forassign(...)actions, which are prioritized and executed first. When.preserveActionOrderis set totrue,assign(...)actions will not be prioritized, and will instead run in order. As a result, actions will capture the intermediatecontextvalues instead of the resultingcontextvalue from allassign(...)actions.// With `.preserveActionOrder: true` const machine = createMachine({ context: { count: 0 }, entry: [ ctx => console.log(ctx.count), // 0 assign({ count: ctx => ctx.count + 1 }), ctx => console.log(ctx.count), // 1 assign({ count: ctx => ctx.count + 1 }), ctx => console.log(ctx.count) // 2 ], preserveActionOrder: true }); // With `.preserveActionOrder: false` (default) const machine = createMachine({ context: { count: 0 }, entry: [ ctx => console.log(ctx.count), // 2 assign({ count: ctx => ctx.count + 1 }), ctx => console.log(ctx.count), // 2 assign({ count: ctx => ctx.count + 1 }), ctx => console.log(ctx.count) // 2 ] // preserveActionOrder: false });Add type for
Symbol.observableto theInterpreterto improve the compatibility with RxJS.Existing actors can now be identified in
spawn(...)calls by providing anid. This allows them to be referenced by string:const machine = createMachine({ context: () => ({ someRef: spawn(someExistingRef, 'something') }), on: { SOME_EVENT: { actions: send('AN_EVENT', { to: 'something' }) } } });
Minor Changes
There is a new
.preserveActionOrder(default:false) setting in the machine configuration that preserves the order of actions when set totrue. Normally, actions are executed in order except forassign(...)actions, which are prioritized and executed first. When.preserveActionOrderis set totrue,assign(...)actions will not be prioritized, and will instead run in order. As a result, actions will capture the intermediatecontextvalues instead of the resultingcontextvalue from allassign(...)actions.// With `.preserveActionOrder: true` const machine = createMachine({ context: { count: 0 }, entry: [ ctx => console.log(ctx.count), // 0 assign({ count: ctx => ctx.count + 1 }), ctx => console.log(ctx.count), // 1 assign({ count: ctx => ctx.count + 1 }), ctx => console.log(ctx.count) // 2 ], preserveActionOrder: true }); // With `.preserveActionOrder: false` (default) const machine = createMachine({ context: { count: 0 }, entry: [ ctx => console.log(ctx.count), // 2 assign({ count: ctx => ctx.count + 1 }), ctx => console.log(ctx.count), // 2 assign({ count: ctx => ctx.count + 1 }), ctx => console.log(ctx.count) // 2 ] // preserveActionOrder: false });
Patch Changes
Add type for
Symbol.observableto theInterpreterto improve the compatibility with RxJS.Existing actors can now be identified in
spawn(...)calls by providing anid. This allows them to be referenced by string:const machine = createMachine({ context: () => ({ someRef: spawn(someExistingRef, 'something') }), on: { SOME_EVENT: { actions: send('AN_EVENT', { to: 'something' }) } } });There are two new helper types for extracting
contextandeventtypes:ContextFrom<T>which extracts thecontextfrom any type that uses contextEventFrom<T>which extracts theeventtype (which extendsEventObject) from any type which uses events
4.22.0
6 Jul 2021The model created from
createModel(...)now provides a.createMachine(...)method that does not require passing any generic type parameters:const model = createModel(/* ... */); -const machine = createMachine<typeof model>(/* ... */); +const machine = model.createMachine(/* ... */);
Actors can now be invoked/spawned from reducers using the
fromReducer(...)behavior creator:import { fromReducer } from 'xstate/lib/behaviors'; type CountEvent = { type: 'INC' } | { type: 'DEC' }; const countReducer = (count: number, event: CountEvent): number => { if (event.type === 'INC') { return count + 1; } else if (event.type === 'DEC') { return count - 1; } return count; }; const countMachine = createMachine({ invoke: { id: 'count', src: () => fromReducer(countReducer, 0) }, on: { INC: { actions: forwardTo('count') }, DEC: { actions: forwardTo('count') } } });Actors can now be spawned directly in the initial
machine.contextusing lazy initialization, avoiding the need for intermediate states and unsafe typings for immediately spawned actors:const machine = createMachine<{ ref: ActorRef<SomeEvent> }>({ context: () => ({ ref: spawn(anotherMachine, 'some-id') // spawn immediately! }) // ... });
4.20.2
1 Jul 2021Reading the note…
4.20.1
25 Jun 2021Reading the note…
4.20.0
1 Jun 2021All spawned and invoked actors now have a
.getSnapshot()method, which allows you to retrieve the latest value emitted from that actor. That value may beundefinedif no value has been emitted yet.const machine = createMachine({ context: { promiseRef: null }, initial: 'pending', states: { pending: { entry: assign({ promiseRef: () => spawn(fetch(/* ... */), 'some-promise') }) } } }); const service = interpret(machine) .onTransition(state => { // Read promise value synchronously const resolvedValue = state.context.promiseRef?.getSnapshot(); // => undefined (if promise not resolved yet) // => { ... } (resolved data) }) .start(); // ...Preserve StateMachine type when .withConfig() and .withContext() modifiers are used on a machine.
4.19.2
26 May 2021Reading the note…
4.19.1
5 May 2021Reading the note…
4.19.0
29 Apr 2021Tags can now be added to state node configs under the
.tagsproperty:const machine = createMachine({ initial: 'green', states: { green: { tags: 'go' // single tag }, yellow: { tags: 'go' }, red: { tags: ['stop', 'other'] // multiple tags } } });You can query whether a state has a tag via
state.hasTag(tag):const canGo = state.hasTag('go'); // => `true` if in 'green' or 'yellow' stateIn callback invokes, the types of
callbackandonReceiveare properly scoped to the machine TEvent.
4.18.0
16 Apr 2021Allow machines to communicate with the inspector even in production builds.
There is now support for "combinatorial machines" (state machines that only have one state):
const testMachine = createMachine({ context: { value: 42 }, on: { INC: { actions: assign({ value: ctx => ctx.value + 1 }) } } });These machines omit the
initialandstateproperties, as the entire machine is treated as a single state.Provide a convenience type for getting the
Interpretertype based on theStateMachinetype by transferring all generic parameters onto it. It can be used like this:InterpreterFrom<typeof machine>
4.17.1
27 Mar 2021Reading the note…
4.17.0
21 Mar 2021The
schemaproperty has been introduced to the machine config passed intocreateMachine(machineConfig), which allows you to provide metadata for the following:This metadata can be accessed as-is from
machine.schema:const machine = createMachine({ schema: { // Example in JSON Schema (anything can be used) context: { type: 'object', properties: { foo: { type: 'string' }, bar: { type: 'number' }, baz: { type: 'object', properties: { one: { type: 'string' } } } } }, events: { FOO: { type: 'object' }, BAR: { type: 'object' } } } // ... });Additionally, the new
createSchema()identity function allows any schema "metadata" to be represented by a specific type, which makes type inference easier without having to specify generic types:import { createSchema, createMachine } from 'xstate'; // Both `context` and `events` are inferred in the rest of the machine! const machine = createMachine({ schema: { context: createSchema<{ count: number }>(), // No arguments necessary events: createSchema<{ type: 'FOO' } | { type: 'BAR' }>() } // ... });Event creators can now be modeled inside of the 2nd argument of
createModel(), and types for bothcontextandeventswill be inferred properly increateMachine()when given thetypeof modelas the first generic parameter.import { createModel } from 'xstate/lib/model'; const userModel = createModel( // initial context { name: 'David', age: 30 }, // creators (just events for now) { events: { updateName: (value: string) => ({ value }), updateAge: (value: number) => ({ value }), anotherEvent: () => ({}) // no payload } } ); const machine = createMachine<typeof userModel>({ context: userModel.initialContext, initial: 'active', states: { active: { on: { updateName: { /* ... */ }, updateAge: { /* ... */ } } } } }); const nextState = machine.transition( undefined, userModel.events.updateName('David') );
4.16.2
7 Feb 2021Reading the note…
4.16.1
5 Feb 2021Reading the note…
4.16.0
15 Jan 2021An opt-in
createModel()helper has been introduced to make it easier to work with typedcontextand events.See #1439 for more details.
import { createMachine } from 'xstate'; import { createModel } from 'xstate/lib/model'; // opt-in, not part of main build interface UserContext { name: string; age: number; } type UserEvents = | { type: 'updateName'; value: string } | { type: 'updateAge'; value: number } const userModel = createModel<UserContext, UserEvents>({ name: 'David', age: 30 }); const assignName = userModel.assign({ name: (_, e) => e.value // correctly typed to `string` }, 'updateName'); // restrict to 'updateName' event const machine = createMachine<UserContext, UserEvents>({ context: userModel.context, initial: 'active', states: { active: { on: { updateName: { actions: assignName } } } } });
4.15.4
6 Jan 2021Reading the note…
4.15.3
29 Dec 2020Reading the note…
4.15.2
23 Dec 2020Reading the note…
4.15.1
7 Dec 2020Reading the note…
4.15.0
6 Dec 2020Spawned/invoked actors and interpreters are now typed as extending
ActorRef(e.g.,SpawnedActorRef) rather thanActororInterpreter. This unification of types should make it more straightforward to provide actor types:import { - Actor + ActorRef } from 'xstate'; // ... interface SomeContext { - server?: Actor; + server?: ActorRef<ServerEvent>; }It's also easier to specify the type of a spawned/invoked machine with
ActorRefFrom:import { createMachine, - Actor + ActorRefFrom } from 'xstate'; const serverMachine = createMachine<ServerContext, ServerEvent>({ // ... }); interface SomeContext { - server?: Actor; // difficult to type + server?: ActorRefFrom<typeof serverMachine>; }Fixed an issue with history state entering a wrong state if the most recent visit in its parent has been caused by a transient transition.
4.14.1
25 Nov 2020Reading the note…
4.14.0
5 Nov 2020Expressions can now be used in the
stop()action creator:// ... actions: stop(context => context.someActor);
The return type of
spawn(machine)will now beActor<State<TContext, TEvent>, TEvent>, which is a supertype ofInterpreter<...>.Exit actions will now be properly called when an invoked machine reaches its final state. See #1109 for more details.
Minor Changes
Expressions can now be used in the
stop()action creator:// ... actions: stop(context => context.someActor);
Patch Changes
The return type of
spawn(machine)will now beActor<State<TContext, TEvent>, TEvent>, which is a supertype ofInterpreter<...>.Exit actions will now be properly called when an invoked machine reaches its final state. See #1109 for more details.
The
state.childrenproperty now properly shows all spawned and invoked actors. See #795 for more details.Added
statusproperty on theInterpreter- this can be used to differentiate not started, running and stopped interpreters. This property is best compared to values on the newInterpreterStatusexport.
4.13.0
27 Aug 2020Fix type
ExtractStateValueso that it generates a type actually describing aState.valueFixed an issue with not being able to run XState in Web Workers due to assuming that
windoworglobalobject is available in the executing environment, but none of those are actually available in the Web Workers context.
Minor Changes
Fix type
ExtractStateValueso that it generates a type actually describing aState.value
Patch Changes
Improved TypeScript type-checking performance a little bit by using distributive conditional type within
TransitionsConfigArraydeclarations instead of a mapped type. Kudos to @amcasey, some discussion around this can be found hereFixed an issue with not being able to run XState in Web Workers due to assuming that
windoworglobalobject is available in the executing environment, but none of those are actually available in the Web Workers context.Fixed an issue with spawned actors being spawned multiple times when they got spawned in an initial state of a child machine that is invoked in the initial state of a parent machine.
Illustrating example for curious readers.
const child = createMachine({ initial: 'bar', context: {}, states: { bar: { entry: assign({ promise: () => { return spawn(() => Promise.resolve('answer')); } }) } } }); const parent = createMachine({ initial: 'foo', states: { foo: { invoke: { src: child, onDone: 'end' } }, end: { type: 'final' } } }); interpret(parent).start();
4.12.0
17 Aug 2020The
Actiontype was simplified, and as a result, you should see better TypeScript performance.The
invoke.srcproperty now accepts an object that describes the invoke source with itstypeand other related metadata. This can be read from theservicesoption in themeta.srcargument:const machine = createMachine( { initial: 'searching', states: { searching: { invoke: { src: { type: 'search', endpoint: 'example.com' } // ... } // ... } } }, { services: { search: (context, event, { src }) => { console.log(src); // => { endpoint: 'example.com' } } } } );Specifying a string for
invoke.srcwill continue to work the same; e.g., ifsrc: 'search'was specified, this would be the same assrc: { type: 'search' }.All
TTypestatetype parameters default to{ value: any; context: TContext }now and the parametrized type is passed correctly between various types which results in more accurate types involving typestates.
Minor Changes
The
Actiontype was simplified, and as a result, you should see better TypeScript performance.
The
invoke.srcproperty now accepts an object that describes the invoke source with itstypeand other related metadata. This can be read from theservicesoption in themeta.srcargument:const machine = createMachine( { initial: 'searching', states: { searching: { invoke: { src: { type: 'search', endpoint: 'example.com' } // ... } // ... } } }, { services: { search: (context, event, { src }) => { console.log(src); // => { endpoint: 'example.com' } } } } );Specifying a string for
invoke.srcwill continue to work the same; e.g., ifsrc: 'search'was specified, this would be the same assrc: { type: 'search' }.
All
TTypestatetype parameters default to{ value: any; context: TContext }now and the parametrized type is passed correctly between various types which results in more accurate types involving typestates.
Patch Changes
Fixed an issue with initial state of invoked machines being read without custom data passed to them which could lead to a crash when evaluating transient transitions for the initial state.
The "Attempted to spawn an Actor [...] outside of a service. This will have no effect." warnings are now silenced for "lazily spawned" actors, which are actors that aren't immediately active until the function that creates them are called:
// ⚠️ "active" actor - will warn spawn(somePromise); // 🕐 "lazy" actor - won't warn spawn(() => somePromise); // 🕐 machines are also "lazy" - won't warn spawn(someMachine);
It is recommended that all
spawn(...)-ed actors are lazy, to avoid accidentally initializing them e.g., when readingmachine.initialStateor calculating otherwise pure transitions. In V5, this will be enforced.
Fixed a type returned by a
raiseaction - it's nowRaiseAction<TEvent> | SendAction<TContext, AnyEventObject, TEvent>instead ofRaiseAction<TEvent> | SendAction<TContext, TEvent, TEvent>. This makes it comaptible in a broader range of scenarios.
Narrowed the
ServiceConfigtype definition to use a specific event type to prevent compilation errors on strictly-typedMachineOptions.
The JSON definition for
stateNode.invokeobjects will no longer include theonDoneandonErrortransitions, since those transitions are already merged into thetransitionsarray. This solves the issue of reviving a serialized machine from JSON, where before, theonDoneandonErrortransitions for invocations were wrongly duplicated.
4.11.0
2 Jul 2020- Breaking
Improved type inference for
InvokeConfig['data']. This has required renamingdataproperty onStateNodeinstances todoneData. This property was never meant to be a part of the public API, so we don't consider this to be a breaking change. - Deprecated
New property introduced for eventless (transient) transitions:
always, which indicates a transition that is always taken when in that state. Empty string transition configs for transient transitions are deprecated in favor ofalways:// ... states: { playing: { + always: [ + { target: 'win', cond: 'didPlayerWin' }, + { target: 'lose', cond: 'didPlayerLose' }, + ], on: { // ⚠️ Deprecation warning - '': [ - { target: 'win', cond: 'didPlayerWin' }, - { target: 'lose', cond: 'didPlayerLose' }, - ] } } } // ...The old empty string syntax (
'': ...) will continue to work until V5. The resolved value of the
invoke.dataproperty is now available in the "invoke meta" object, which is passed as the 3rd argument to the service creator inoptions.services. This will work for all types of invoked services now, including promises, observables, and callbacks.const machine = createMachine({ initial: 'pending', context: { id: 42 }, states: { pending: { invoke: { src: 'fetchUser', data: { userId: (context) => context.id }, onDone: 'success' } }, success: { type: 'final' } } }, { services: { fetchUser: (ctx, _, { data }) => { return fetch(`some/api/user/${data.userId}`) .then(response => response.json()); } } }
Minor Changes
- Breaking
Improved type inference for
InvokeConfig['data']. This has required renamingdataproperty onStateNodeinstances todoneData. This property was never meant to be a part of the public API, so we don't consider this to be a breaking change. The resolved value of the
invoke.dataproperty is now available in the "invoke meta" object, which is passed as the 3rd argument to the service creator inoptions.services. This will work for all types of invoked services now, including promises, observables, and callbacks.const machine = createMachine({ initial: 'pending', context: { id: 42 }, states: { pending: { invoke: { src: 'fetchUser', data: { userId: (context) => context.id }, onDone: 'success' } }, success: { type: 'final' } } }, { services: { fetchUser: (ctx, _, { data }) => { return fetch(`some/api/user/${data.userId}`) .then(response => response.json()); } } }- Deprecated
New property introduced for eventless (transient) transitions:
always, which indicates a transition that is always taken when in that state. Empty string transition configs for transient transitions are deprecated in favor ofalways:// ... states: { playing: { + always: [ + { target: 'win', cond: 'didPlayerWin' }, + { target: 'lose', cond: 'didPlayerLose' }, + ], on: { // ⚠️ Deprecation warning - '': [ - { target: 'win', cond: 'didPlayerWin' }, - { target: 'lose', cond: 'didPlayerLose' }, - ] } } } // ...The old empty string syntax (
'': ...) will continue to work until V5.
Patch Changes
StateMachine<any, any, any>is no longer a part of theInvokeConfigtype, but rather it creates a union withInvokeConfigin places where it is needed. This change shouldn't affect consumers' code.
4.10.0
20 May 2020The types for the
send()andsendParent()action creators have been changed to fix the issue of only being able to send events that the machine can receive. In reality, a machine can and should send events to other actors that it might not be able to receive itself. See #711 for more information.Previously,
state.matches(...)was problematic because it was castingstatetoneverif it didn't match the state value. This is now fixed by making theTypestateresolution more granular.Actions from a restored state provided as a custom initial state to
interpret(machine).start(initialState)are now executed properly. See #1174 for more information.
Minor Changes
The types for the
send()andsendParent()action creators have been changed to fix the issue of only being able to send events that the machine can receive. In reality, a machine can and should send events to other actors that it might not be able to receive itself. See #711 for more information.Previously,
state.matches(...)was problematic because it was castingstatetoneverif it didn't match the state value. This is now fixed by making theTypestateresolution more granular.Actions from a restored state provided as a custom initial state to
interpret(machine).start(initialState)are now executed properly. See #1174 for more information.
Patch Changes
Fix passing state schema into State generic
Fixed an issue with invoked service not being correctly started if other service got stopped in a subsequent microstep (in response to raised or null event).
Delayed transitions defined using
afterwere previously causing a circular dependency when the machine was converted using.toJSON(). This has now been fixed.Fixed an issue with
chooseandpurenot being able to use actions defined in options.XState will now warn if you define an
.onDonetransition on the root node. Root nodes which are "done" represent the machine being in its final state, and can no longer accept any events. This has been reported as confusing in #1111.
4.9.1
17 Apr 2020Reading the note…
4.9.0
15 Apr 2020Simplify the
TransitionConfigArrayandTransitionConfigMaptypes in order to fix excessively deep type instantiation TypeScript reports. This addresses #1015.Added support for conditional actions. It's possible now to have actions executed based on conditions using following:
entry: [ choose([ { cond: ctx => ctx > 100, actions: raise('TOGGLE') }, { cond: 'hasMagicBottle', actions: [assign(ctx => ({ counter: ctx.counter + 1 }))] }, { actions: ['fallbackAction'] } ]) ];It works very similar to the if-else syntax where only the first matched condition is causing associated actions to be executed and the last ones can be unconditional (serving as a general fallback, just like else branch).
Cleanup internal structures upon receiving termination events from spawned actors.
Minor Changes
Simplify the
TransitionConfigArrayandTransitionConfigMaptypes in order to fix excessively deep type instantiation TypeScript reports. This addresses #1015.Added support for conditional actions. It's possible now to have actions executed based on conditions using following:
entry: [ choose([ { cond: ctx => ctx > 100, actions: raise('TOGGLE') }, { cond: 'hasMagicBottle', actions: [assign(ctx => ({ counter: ctx.counter + 1 }))] }, { actions: ['fallbackAction'] } ]) ];It works very similar to the if-else syntax where only the first matched condition is causing associated actions to be executed and the last ones can be unconditional (serving as a general fallback, just like else branch).
Patch Changes
Cleanup internal structures upon receiving termination events from spawned actors.
Fixed an issue with data expressions of root's final nodes being called twice.
This change carries forward the typestate type information encoded in the arguments of the following functions and assures that the return type also has the same typestate type information:
Cloned state machine returned by
.withConfig..stategetter defined for services.startmethod of services.
Loosened event type for
SendAction<TContext, AnyEventObject>
4.8.0
4 Mar 2020The machine can now be safely JSON-serialized, using
JSON.stringify(machine). The shape of this serialization is defined inmachine.schema.jsonand reflected inmachine.definition.Note that
onEntryandonExithave been deprecated in the definition in favor ofentryandexit.Fixed memory leak -
Stateobjects had been retained in closures.
4.7.8
4 Feb 2020Reading the note…
4.7.7
24 Jan 2020Reading the note…
4.7.6
7 Jan 2020Reading the note…
4.7.5
28 Dec 2019Reading 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.