xstate 6.0.0-alpha.8 → 6.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +223 -78
- package/bin/agent.js +347 -0
- package/bin/xstate.js +52 -0
- package/dist/createActor-25900f76.cjs.js +7015 -0
- package/dist/createActor-551369be.development.esm.js +7175 -0
- package/dist/createActor-a49ae0ce.development.cjs.js +7289 -0
- package/dist/createActor-cbe3abac.esm.js +6902 -0
- package/dist/declarations/src/SimulatedClock.d.ts +2 -1
- package/dist/declarations/src/State.d.ts +66 -5
- package/dist/declarations/src/StateMachine.d.ts +107 -32
- package/dist/declarations/src/StateNode.d.ts +21 -16
- package/dist/declarations/src/actions.d.ts +11 -6
- package/dist/declarations/src/actors/callback.d.ts +11 -2
- package/dist/declarations/src/actors/index.d.ts +6 -5
- package/dist/declarations/src/actors/listener.d.ts +8 -3
- package/dist/declarations/src/actors/logic.d.ts +42 -52
- package/dist/declarations/src/actors/observable.d.ts +15 -2
- package/dist/declarations/src/actors/promise.d.ts +90 -22
- package/dist/declarations/src/actors/subscription.d.ts +9 -3
- package/dist/declarations/src/assert.d.ts +1 -0
- package/dist/declarations/src/base.types.d.ts +102 -0
- package/dist/declarations/src/createActor.d.ts +101 -27
- package/dist/declarations/src/createMachine.d.ts +38 -17
- package/dist/declarations/src/delay.d.ts +8 -0
- package/dist/declarations/src/durable/index.d.ts +231 -0
- package/dist/declarations/src/effectDescriptor.d.ts +95 -0
- package/dist/declarations/src/eventTypes.d.ts +9 -0
- package/dist/declarations/src/fsm/index.d.ts +2 -0
- package/dist/declarations/src/fsm.d.ts +169 -0
- package/dist/declarations/src/graph/adjacency.d.ts +6 -3
- package/dist/declarations/src/graph/graph.d.ts +6 -3
- package/dist/declarations/src/graph/index.d.ts +2 -3
- package/dist/declarations/src/graph/pathFromEvents.d.ts +5 -2
- package/dist/declarations/src/graph/shortestPaths.d.ts +5 -3
- package/dist/declarations/src/graph/simplePaths.d.ts +5 -3
- package/dist/declarations/src/graph/types.d.ts +113 -59
- package/dist/declarations/src/hotSwap.d.ts +18 -0
- package/dist/declarations/src/index.d.ts +28 -19
- package/dist/declarations/src/inspection.d.ts +24 -1
- package/dist/declarations/src/machineFromJSON.d.ts +171 -0
- package/dist/declarations/src/machineSchemas.d.ts +27 -0
- package/dist/declarations/src/machineVersion.types.d.ts +53 -0
- package/dist/declarations/src/machineVersions.d.ts +103 -0
- package/dist/declarations/src/mapState.d.ts +2 -0
- package/dist/declarations/src/persist/index.d.ts +36 -0
- package/dist/declarations/src/persistedSnapshotValidation.d.ts +18 -0
- package/dist/declarations/src/runtimeHelpers.d.ts +43 -0
- package/dist/declarations/src/schema.types.d.ts +31 -4
- package/dist/declarations/src/serialize.d.ts +39 -28
- package/dist/declarations/src/setup.d.ts +1086 -147
- package/dist/declarations/src/spawn.d.ts +6 -4
- package/dist/declarations/src/stateUtils.d.ts +57 -14
- package/dist/declarations/src/system.d.ts +178 -17
- package/dist/declarations/src/systemTransition.d.ts +108 -0
- package/dist/declarations/src/toPromise.d.ts +1 -0
- package/dist/declarations/src/transition.d.ts +48 -10
- package/dist/declarations/src/transitionActions.d.ts +22 -4
- package/dist/declarations/src/typeUtils.d.ts +51 -0
- package/dist/declarations/src/types.d.ts +835 -318
- package/dist/declarations/src/types.v6.d.ts +547 -104
- package/dist/declarations/src/utils.d.ts +38 -8
- package/dist/declarations/src/validation/index.d.ts +49 -0
- package/dist/declarations/src/validation.types.d.ts +29 -0
- package/dist/declarations/src/waitFor.d.ts +1 -0
- package/dist/effectDescriptor-2fa27c54.cjs.js +351 -0
- package/dist/effectDescriptor-321a8ce9.development.esm.js +343 -0
- package/dist/effectDescriptor-d8b0f749.esm.js +343 -0
- package/dist/effectDescriptor-f73da4ec.development.cjs.js +351 -0
- package/dist/machineSchemas-45c21bc2.esm.js +1292 -0
- package/dist/machineSchemas-6d96bef4.development.cjs.js +1379 -0
- package/dist/machineSchemas-88d01821.cjs.js +1300 -0
- package/dist/machineSchemas-b5736804.development.esm.js +1371 -0
- package/dist/schema.types-0ecd17b8.esm.js +71 -0
- package/dist/schema.types-15a68ddc.cjs.js +74 -0
- package/dist/schema.types-1c16f035.development.cjs.js +74 -0
- package/dist/schema.types-1cd4652e.development.esm.js +71 -0
- package/dist/validation-05f1d517.esm.js +8 -0
- package/dist/validation-4561b43c.cjs.js +10 -0
- package/dist/validation-e69470ad.development.esm.js +8 -0
- package/dist/validation-f2714a35.development.cjs.js +10 -0
- package/dist/xstate-actors.cjs.js +1068 -12
- package/dist/xstate-actors.cjs.mjs +2 -4
- package/dist/xstate-actors.development.cjs.js +1068 -12
- package/dist/xstate-actors.development.cjs.mjs +2 -4
- package/dist/xstate-actors.development.esm.js +1064 -1
- package/dist/xstate-actors.esm.js +1064 -1
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-durable.cjs.d.mts +2 -0
- package/dist/xstate-durable.cjs.d.ts +2 -0
- package/dist/xstate-durable.cjs.js +513 -0
- package/dist/xstate-durable.cjs.mjs +5 -0
- package/dist/xstate-durable.development.cjs.js +513 -0
- package/dist/xstate-durable.development.cjs.mjs +5 -0
- package/dist/xstate-durable.development.esm.js +507 -0
- package/dist/xstate-durable.esm.js +507 -0
- package/dist/xstate-durable.umd.min.js +2 -0
- package/dist/xstate-durable.umd.min.js.map +1 -0
- package/dist/xstate-fsm.cjs.d.mts +2 -0
- package/dist/xstate-fsm.cjs.d.ts +2 -0
- package/dist/xstate-fsm.cjs.js +111 -0
- package/dist/xstate-fsm.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.cjs.js +111 -0
- package/dist/xstate-fsm.development.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.esm.js +105 -0
- package/dist/xstate-fsm.esm.js +105 -0
- package/dist/xstate-fsm.umd.min.js +2 -0
- package/dist/xstate-fsm.umd.min.js.map +1 -0
- package/dist/xstate-graph.cjs.js +173 -457
- package/dist/xstate-graph.cjs.mjs +2 -5
- package/dist/xstate-graph.development.cjs.js +173 -457
- package/dist/xstate-graph.development.cjs.mjs +2 -5
- package/dist/xstate-graph.development.esm.js +171 -451
- package/dist/xstate-graph.esm.js +171 -451
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate-persist.cjs.d.mts +2 -0
- package/dist/xstate-persist.cjs.d.ts +2 -0
- package/dist/xstate-persist.cjs.js +314 -0
- package/dist/xstate-persist.cjs.mjs +6 -0
- package/dist/xstate-persist.development.cjs.js +325 -0
- package/dist/xstate-persist.development.cjs.mjs +6 -0
- package/dist/xstate-persist.development.esm.js +319 -0
- package/dist/xstate-persist.esm.js +308 -0
- package/dist/xstate-persist.umd.min.js +2 -0
- package/dist/xstate-persist.umd.min.js.map +1 -0
- package/dist/xstate-validation.cjs.d.mts +2 -0
- package/dist/xstate-validation.cjs.d.ts +2 -0
- package/dist/xstate-validation.cjs.js +330 -0
- package/dist/xstate-validation.cjs.mjs +5 -0
- package/dist/xstate-validation.development.cjs.js +330 -0
- package/dist/xstate-validation.development.cjs.mjs +5 -0
- package/dist/xstate-validation.development.esm.js +324 -0
- package/dist/xstate-validation.esm.js +324 -0
- package/dist/xstate-validation.umd.min.js +2 -0
- package/dist/xstate-validation.umd.min.js.map +1 -0
- package/dist/xstate.cjs.js +2486 -1430
- package/dist/xstate.cjs.mjs +23 -13
- package/dist/xstate.development.cjs.js +2486 -1430
- package/dist/xstate.development.cjs.mjs +23 -13
- package/dist/xstate.development.esm.js +2445 -1398
- package/dist/xstate.esm.js +2445 -1398
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/docs/actions.md +75 -0
- package/docs/actor-logic.md +250 -0
- package/docs/actors.md +64 -0
- package/docs/agents.md +132 -0
- package/docs/api-stability.json +4287 -0
- package/docs/async-logic.md +75 -0
- package/docs/async-requests.md +157 -0
- package/docs/backend-workflows.md +124 -0
- package/docs/cancellation.md +42 -0
- package/docs/cheatsheet.md +563 -0
- package/docs/choice-states.md +109 -0
- package/docs/choose-xstate.md +47 -0
- package/docs/configuration.md +161 -0
- package/docs/context.md +67 -0
- package/docs/create-actor.md +159 -0
- package/docs/data-and-effects.md +48 -0
- package/docs/delays.md +81 -0
- package/docs/durable-execution.md +520 -0
- package/docs/emitted-events.md +146 -0
- package/docs/errors.md +812 -0
- package/docs/examples.md +75 -0
- package/docs/faq.md +60 -0
- package/docs/final-states.md +149 -0
- package/docs/forms-and-wizards.md +166 -0
- package/docs/frameworks.md +69 -0
- package/docs/fsm.md +164 -0
- package/docs/glossary.md +68 -0
- package/docs/guards.md +137 -0
- package/docs/history-states.md +161 -0
- package/docs/how-xstate-runs-machines.md +86 -0
- package/docs/index.md +74 -0
- package/docs/input-output.md +69 -0
- package/docs/inspect-actor-systems.md +118 -0
- package/docs/inspection.md +75 -0
- package/docs/internal-events.md +156 -0
- package/docs/invoke.md +371 -0
- package/docs/lifecycle-and-errors.md +48 -0
- package/docs/listen-and-subscribe.md +126 -0
- package/docs/model-based-testing.md +321 -0
- package/docs/modeling.md +40 -0
- package/docs/parallel-states.md +182 -0
- package/docs/persist-and-restore-actors.md +120 -0
- package/docs/persistence.md +312 -0
- package/docs/quick-start.md +55 -0
- package/docs/retries-and-timeouts.md +122 -0
- package/docs/route-states.md +104 -0
- package/docs/scxml.md +92 -0
- package/docs/selectors.md +99 -0
- package/docs/serialization.md +127 -0
- package/docs/setup-and-provide.md +273 -0
- package/docs/snapshots.md +134 -0
- package/docs/spawn.md +212 -0
- package/docs/state-input.md +162 -0
- package/docs/statecharts.md +54 -0
- package/docs/states-events-transitions.md +82 -0
- package/docs/states.md +168 -0
- package/docs/system-transitions.md +172 -0
- package/docs/systems.md +166 -0
- package/docs/testing.md +152 -0
- package/docs/timeouts.md +125 -0
- package/docs/transition-functions.md +89 -0
- package/docs/transitions.md +187 -0
- package/docs/troubleshooting.md +56 -0
- package/docs/tutorial.md +481 -0
- package/docs/typescript.md +213 -0
- package/docs/typestates.md +112 -0
- package/docs/utilities.md +39 -0
- package/docs/why-state-machines.md +59 -0
- package/docs/xstate-v5-to-v6.md +1923 -0
- package/docs/your-first-machine.md +79 -0
- package/durable/package.json +8 -0
- package/fsm/package.json +8 -0
- package/package.json +72 -10
- package/persist/package.json +8 -0
- package/validation/package.json +8 -0
- package/actions/package.json +0 -8
- package/dev/package.json +0 -8
- package/dist/StateMachine-0aa98f54.development.esm.js +0 -746
- package/dist/StateMachine-aef700df.cjs.js +0 -732
- package/dist/StateMachine-d4931336.esm.js +0 -729
- package/dist/StateMachine-da872dde.development.cjs.js +0 -749
- package/dist/declarations/src/createMachineFromConfig.d.ts +0 -177
- package/dist/declarations/src/getNextSnapshot.d.ts +0 -37
- package/dist/declarations/src/graph/TestModel.d.ts +0 -70
- package/dist/declarations/src/graph/pathGenerators.d.ts +0 -4
- package/dist/index-219cb621.development.cjs.js +0 -4476
- package/dist/index-2f2fbd9b.development.esm.js +0 -4421
- package/dist/index-559ceab3.cjs.js +0 -4437
- package/dist/index-8828376f.esm.js +0 -4382
- package/guards/package.json +0 -8
- package/invoke/package.json +0 -4
package/docs/invoke.md
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Invoke actors
|
|
3
|
+
description: Run a child actor for the lifetime of a state.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Use `invoke` to start a child actor when a state is entered. The child stops when that state is exited.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
const machine = createMachine({
|
|
10
|
+
initial: 'loading',
|
|
11
|
+
states: {
|
|
12
|
+
loading: {
|
|
13
|
+
invoke: {
|
|
14
|
+
src: loadUser,
|
|
15
|
+
input: ({ context }) => ({ id: context.userId }),
|
|
16
|
+
onDone: { target: 'ready' },
|
|
17
|
+
onError: { target: 'failed' },
|
|
18
|
+
timeout: 5_000,
|
|
19
|
+
onTimeout: { target: 'timedOut' }
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
ready: {},
|
|
23
|
+
failed: {},
|
|
24
|
+
timedOut: {}
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Use an actor instead of an action when work is async, can be canceled, sends snapshots or affects the next state. Common examples are payment authorization and file uploads.
|
|
30
|
+
|
|
31
|
+
## Invoke or spawn
|
|
32
|
+
|
|
33
|
+
Invoking and [spawning](spawn.md) both create a child actor. They differ in who controls the child's lifetime.
|
|
34
|
+
|
|
35
|
+
- **Invoke** ties the child to a state. Entering the state starts the child, exiting the state stops it, and `onDone` and `onError` transitions handle its completion.
|
|
36
|
+
- **Spawn** creates a child whose lifetime you manage. `enq.spawn(...)` in a transition function, or `spawn` in a context initializer, starts the child. It runs until it completes, until `enq.stop(ref)` stops it, or until the parent stops. Exiting the state that spawned it does not stop it.
|
|
37
|
+
|
|
38
|
+
| | Invoke | Spawn |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| Lifetime | The invoking state: started on entry, stopped on exit | Until it completes, `enq.stop(ref)`, or the parent stops |
|
|
41
|
+
| Declared in | `invoke` on a state node or the machine root | `enq.spawn(...)` in a transition function, or `spawn` in a context initializer |
|
|
42
|
+
| How many | Fixed by the config | Any number, decided at runtime |
|
|
43
|
+
| Completion handling | `onDone`, `onError`, `onSnapshot` transitions | `enq.subscribeTo(...)`, `enq.listen(...)` |
|
|
44
|
+
| Persistence | Restored with the parent, including inline logic | Restored with the parent when the source is registered in `actors`; inline logic cannot be persisted |
|
|
45
|
+
|
|
46
|
+
Invoke a payment actor for the `authorizing` state. Spawn one upload actor per selected file, one participant actor per person in a call, or one track actor per queued item in a media player.
|
|
47
|
+
|
|
48
|
+
## Invoke properties
|
|
49
|
+
|
|
50
|
+
| Property | Description |
|
|
51
|
+
| --- | --- |
|
|
52
|
+
| `src` | Required. The [actor logic](actor-logic.md) to run: a logic value, the name of logic registered in `actors`, or a function that returns either. |
|
|
53
|
+
| `id` | Identifier for the child. Defaults to `<stateId>:<index>`, such as `loading:0` for the first invoke of state `loading`. |
|
|
54
|
+
| `input` | [Input](input-output.md) for the child: a value, or a function of `{ context, event, self }`. Required when the logic's input type excludes `undefined`, for example when it declares `schemas.input`. |
|
|
55
|
+
| `registryKey` | Registers the child in the [actor registry](systems.md) under that key. |
|
|
56
|
+
| `timeout` | Milliseconds, or a function of `{ context, event }` returning milliseconds. |
|
|
57
|
+
| `onTimeout` | Transition taken when `timeout` elapses. Required when `timeout` is set. |
|
|
58
|
+
| `onDone` | Transition taken when the child completes. `event.output` holds its output. |
|
|
59
|
+
| `onError` | Transition taken when the child errors. `event.error` holds the error. |
|
|
60
|
+
| `onSnapshot` | Transition taken on each child snapshot. `event.snapshot` holds the snapshot. |
|
|
61
|
+
|
|
62
|
+
Only `src` is required. A state node accepts a single invoke config or an array of them.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
invoke: [
|
|
66
|
+
{ src: heartbeat, id: 'heartbeat' },
|
|
67
|
+
{ src: syncLogic, id: 'sync', onError: { target: 'offline' } }
|
|
68
|
+
]
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
An input mapper receives the parent machine's typed `context` and `event`, including when a registered actor accepts `unknown` or `any` input. Actors with a specific input type still check both static inputs and mapper return values.
|
|
72
|
+
|
|
73
|
+
## Typed inline invokes
|
|
74
|
+
|
|
75
|
+
Use `s.createInvoke(...)` inside a machine created with `s = setup(...)` when actor logic is used in one state. It infers the actor's input, completion output, error and snapshot types without registering the actor in `setup.actors`. For async work, pass the function directly as `src` and declare its schemas in the same invoke config.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { setup, types } from 'xstate';
|
|
79
|
+
|
|
80
|
+
const s = setup({
|
|
81
|
+
schemas: {
|
|
82
|
+
context: types<{ userId: string | undefined; name: string }>()
|
|
83
|
+
},
|
|
84
|
+
states: {
|
|
85
|
+
loading: { schemas: { context: types<{ userId: string }>() } },
|
|
86
|
+
ready: {}
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const machine = s.createMachine({
|
|
91
|
+
context: { userId: '123', name: '' },
|
|
92
|
+
initial: 'loading',
|
|
93
|
+
states: {
|
|
94
|
+
loading: {
|
|
95
|
+
invoke: s.createInvoke({
|
|
96
|
+
schemas: {
|
|
97
|
+
input: types<{ userId: string }>(),
|
|
98
|
+
output: types<{ name: string }>()
|
|
99
|
+
},
|
|
100
|
+
input: ({ context }) => ({ userId: context.userId }),
|
|
101
|
+
src: async ({ input }) => ({ name: input.userId }),
|
|
102
|
+
onDone: ({ event }) => ({
|
|
103
|
+
target: 'ready',
|
|
104
|
+
context: { name: event.output.name }
|
|
105
|
+
})
|
|
106
|
+
})
|
|
107
|
+
},
|
|
108
|
+
ready: {}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Keep the helper call inline: its enclosing state supplies narrowed context, ancestor context, state input and transition targets. In this example, `context.userId` is `string` and `event.output` is `{ name: string }`.
|
|
114
|
+
|
|
115
|
+
For an async `src`, `schemas.input` types the actor input, `schemas.output` checks the function's resolved value and types `onDone.event.output`, and `schemas.error` types `onError.event.error`. Omit the output schema to infer output from the async return value. The function receives `{ input, signal, self, system }` and the async enqueue object, including `emit` and `step`, just like `createAsyncLogic`. Its input comes from the invoke's static value or input mapper; parent context stays in the mapper and transition handlers.
|
|
116
|
+
|
|
117
|
+
You can also pass an existing actor logic value, including machine and callback logic:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
invoke: s.createInvoke({
|
|
121
|
+
src: loadUserLogic,
|
|
122
|
+
input: ({ context }) => ({ userId: context.userId }),
|
|
123
|
+
onDone: ({ event }) => ({ context: { name: event.output.name } })
|
|
124
|
+
})
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
For a logic value, its own schemas determine input, output, error and snapshot types. Declare schemas on that logic rather than repeating them on the invoke.
|
|
128
|
+
|
|
129
|
+
The helper requires `input` when the source's input type excludes `undefined`. Pass a static value or a mapper returning that input type. Logic that accepts `undefined` can omit `input`.
|
|
130
|
+
|
|
131
|
+
Child contracts from `schemas.children` apply whether declared in `setup(...)` or `s.createMachine(...)`: supply a declared `id` and compatible `src`. This check also applies to hoisted configs when used in the machine.
|
|
132
|
+
|
|
133
|
+
The helper supports the usual invoke options, including invoke arrays and setups with other registered actors. Child startup, cancellation, timeouts and persistence follow the normal invoke lifecycle.
|
|
134
|
+
|
|
135
|
+
Keep the source's specific actor logic type to infer its input and output; an `AnyActorLogic` annotation loses that information. Declare an error schema to type errors; otherwise they are `unknown`.
|
|
136
|
+
|
|
137
|
+
A helper call made outside a machine has only setup-level context. To extract a config while keeping a specific state's scope, put the inline helper inside `s.createStateConfig('loading', { invoke: s.createInvoke(...) })`.
|
|
138
|
+
|
|
139
|
+
For a helper extracted outside the machine, use function-form `onDone: ({ event }) => ({ context: ... })` to infer completion output. A targetless object-form `onDone.context` mapper needs an explicit argument annotation.
|
|
140
|
+
|
|
141
|
+
## Actor lifecycle
|
|
142
|
+
|
|
143
|
+
Invoked actors belong to the state that starts them:
|
|
144
|
+
|
|
145
|
+
- entering the state starts the actor
|
|
146
|
+
- leaving the state stops it
|
|
147
|
+
- re-entering the state stops the old actor and starts a new one
|
|
148
|
+
|
|
149
|
+
A state is re-entered by an external transition back to itself, or by a transition with `reenter: true`. A transition that stays inside the invoking state does not restart the child.
|
|
150
|
+
|
|
151
|
+
Invoke on the machine root runs for the whole lifetime of the actor. Root invocations survive ordinary transitions between top-level states, and restart only on a root [transition](transitions.md) with `reenter: true`.
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
const machine = createMachine({
|
|
155
|
+
invoke: { src: connection, id: 'connection' },
|
|
156
|
+
initial: 'idle',
|
|
157
|
+
states: { idle: {}, playing: {} }
|
|
158
|
+
});
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Children are started after the parent snapshot is committed, so a child that immediately sends an event to its parent finds the parent already in the invoking state.
|
|
162
|
+
|
|
163
|
+
## Choosing logic
|
|
164
|
+
|
|
165
|
+
Invoke a machine when the child has states of its own:
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
checkout: {
|
|
169
|
+
invoke: {
|
|
170
|
+
src: paymentMachine,
|
|
171
|
+
id: 'payment',
|
|
172
|
+
input: ({ context }) => ({ amount: context.total }),
|
|
173
|
+
onDone: { target: 'confirmed' }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Invoke [async logic](async-logic.md) for a single request. The child completes with the resolved value and errors with a rejection:
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
const chargeCard = createAsyncLogic({
|
|
182
|
+
run: ({ input, signal }) => createCharge(input.amount, { signal })
|
|
183
|
+
});
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Invoke [callback logic](actor-logic.md) for a subscription that lives as long as the state:
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
playing: {
|
|
190
|
+
invoke: {
|
|
191
|
+
src: createCallbackLogic(({ sendBack }) => {
|
|
192
|
+
const id = setInterval(() => sendBack({ type: 'tick' }), 1000);
|
|
193
|
+
return () => clearInterval(id);
|
|
194
|
+
})
|
|
195
|
+
},
|
|
196
|
+
on: { tick: ({ context }) => ({ context: { time: context.time + 1 } }) }
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
## Reacting to the child
|
|
201
|
+
|
|
202
|
+
`onDone` receives final output, `onError` an unhandled error, and `onSnapshot` each intermediate snapshot.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
invoke: {
|
|
206
|
+
src: uploadMachine,
|
|
207
|
+
onSnapshot: ({ context, event }) => ({
|
|
208
|
+
context: {
|
|
209
|
+
...context,
|
|
210
|
+
progress: event.snapshot.context.progress
|
|
211
|
+
}
|
|
212
|
+
}),
|
|
213
|
+
onDone: { target: 'complete' },
|
|
214
|
+
onError: { target: 'failed' }
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
These are conveniences over lifecycle events. The child sends `xstate.done.actor`, `xstate.error.actor` and `xstate.snapshot.actor` events with an `actorId` payload; `onDone`, `onError` and `onSnapshot` set `matches: { actorId }` for you so each one only handles its own child. Handle the event directly when the transition belongs on an ancestor state:
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
on: {
|
|
222
|
+
'xstate.done.actor': { matches: { actorId: 'payment' }, target: 'confirmed' }
|
|
223
|
+
}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
See [transitions](transitions.md) for `matches` and the full list of lifecycle events.
|
|
227
|
+
|
|
228
|
+
## Timing out an invocation
|
|
229
|
+
|
|
230
|
+
`timeout` bounds how long the invocation may run. When it elapses, `onTimeout` is taken. A handler that exits the owning state stops the child; a targetless handler leaves it running unless it calls `enq.stop(...)`. When the child finishes first, the timeout is canceled.
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
authorizing: {
|
|
234
|
+
invoke: {
|
|
235
|
+
src: authorizePayment,
|
|
236
|
+
timeout: ({ context }) => context.authTimeout,
|
|
237
|
+
onTimeout: { target: 'declined' },
|
|
238
|
+
onDone: { target: 'authorized' }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Setting `timeout` without `onTimeout` throws when the machine is created in development builds. Use `createAsyncLogic({ timeout })` instead when the timeout belongs to the logic rather than to this particular invocation. See [timeouts](timeouts.md).
|
|
244
|
+
|
|
245
|
+
## Referencing the child
|
|
246
|
+
|
|
247
|
+
Invoked children appear on `snapshot.children` under their `id`, and transition functions receive them as `children`:
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
on: {
|
|
251
|
+
cancel: ({ children }, enq) => {
|
|
252
|
+
enq.sendTo(children.payment, { type: 'cancel' });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
A child sends events back through its `parent` argument:
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
const paymentMachine = createMachine({
|
|
261
|
+
on: {
|
|
262
|
+
approve: ({ parent }, enq) => {
|
|
263
|
+
enq.sendTo(parent, { type: 'paymentApproved' });
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
## Persistence
|
|
270
|
+
|
|
271
|
+
Invoked children are persisted with the parent snapshot and restored by `restoreActor(machine, persisted)` from `xstate/persist`. A child restored this way keeps its context but gets a new session.
|
|
272
|
+
|
|
273
|
+
Register logic in `actors` and reference it by name when the persisted snapshot should stay readable and stable across refactors:
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
const machine = createMachine({
|
|
277
|
+
actors: { chargeCard },
|
|
278
|
+
initial: 'charging',
|
|
279
|
+
states: {
|
|
280
|
+
charging: { invoke: { src: 'chargeCard', id: 'charge' } }
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
The persisted child then records `src: 'chargeCard'` instead of a generated source name that points back at this invoke config. Either restores, but a named source survives moving the invoke to another state. See [persistence](persistence.md).
|
|
286
|
+
|
|
287
|
+
## Common pitfalls
|
|
288
|
+
|
|
289
|
+
Invoke belongs to the state, not to the transition that led there. This is wrong:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
on: {
|
|
293
|
+
submit: {
|
|
294
|
+
target: 'sending',
|
|
295
|
+
// ❌ invoke is not a transition property
|
|
296
|
+
invoke: { src: sendOrder }
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
Put the invoke on the target state instead, so the actor starts when `sending` is entered and stops when it is left.
|
|
302
|
+
|
|
303
|
+
Invoke also is not the right tool when the child must outlive the state, or when the number of children is dynamic. [Spawn](spawn.md) those instead.
|
|
304
|
+
|
|
305
|
+
## TypeScript
|
|
306
|
+
|
|
307
|
+
Provide named actor logic through `setup({ actors })` or `createMachine({ actors })`. XState correlates `src` with `input`, so a static or mapped input is checked against that logic's input type, and `onDone` sees the output type of that logic.
|
|
308
|
+
|
|
309
|
+
Declare child ids with `schemas.children` to type `children` and to check that each `id` receives compatible logic:
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
setup({}).createMachine({
|
|
313
|
+
schemas: {
|
|
314
|
+
children: {
|
|
315
|
+
payment: z.custom<ActorRefFrom<typeof paymentMachine>>()
|
|
316
|
+
}
|
|
317
|
+
},
|
|
318
|
+
invoke: { id: 'payment', src: paymentMachine }
|
|
319
|
+
});
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
`children.payment` is then typed, `children.other` is a type error, and invoking incompatible logic under `id: 'payment'` is rejected. The id can also be used directly with `enq.sendTo`; the event is checked against the declared actor ref:
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
on: {
|
|
326
|
+
retry: (_, enq) => {
|
|
327
|
+
enq.sendTo('payment', { type: 'retry' });
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
### Typed done and error events
|
|
333
|
+
|
|
334
|
+
When children are declared in `schemas.children`, `entry`, `exit` and transition functions that can receive any event include `xstate.done.actor` and `xstate.error.actor` in their event type, narrowed by `actorId`. After narrowing, `event.actorId` is the declared id and `event.output` has the child's output type. `event.error` is `unknown`. A handler under `on` for a user event, such as `on.retry`, still receives only that event.
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
setup({
|
|
338
|
+
actors: { fetchUser },
|
|
339
|
+
schemas: {
|
|
340
|
+
events: { retry: z.object({}) },
|
|
341
|
+
children: {
|
|
342
|
+
fetch: z.custom<ActorRefFrom<typeof fetchUser>>()
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}).createMachine({
|
|
346
|
+
invoke: { id: 'fetch', src: 'fetchUser' },
|
|
347
|
+
entry: ({ event }) => {
|
|
348
|
+
assertEvent(event, 'xstate.done.actor');
|
|
349
|
+
event.actorId; // 'fetch'
|
|
350
|
+
event.output.name; // string
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
Without `schemas.children`, these events are not part of the event type. Declaring `schemas.events` is not required for the narrowing.
|
|
356
|
+
|
|
357
|
+
## Invoke cheatsheet
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
invoke: {
|
|
361
|
+
id: 'request',
|
|
362
|
+
src: requestLogic,
|
|
363
|
+
input: ({ context }) => context.request,
|
|
364
|
+
registryKey: 'request',
|
|
365
|
+
timeout: 10_000,
|
|
366
|
+
onTimeout: { target: 'timedOut' },
|
|
367
|
+
onDone: { target: 'success' },
|
|
368
|
+
onError: { target: 'failure' },
|
|
369
|
+
onSnapshot: ({ event }) => ({ context: { snapshot: event.snapshot } })
|
|
370
|
+
}
|
|
371
|
+
```
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Lifecycle and errors
|
|
3
|
+
description: Start, stop and observe actors safely.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
An actor begins processing after `start()`. It stops after `stop()`, after reaching a final state or after an unhandled error.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
actor.subscribe({
|
|
10
|
+
next: (snapshot) => console.log(snapshot),
|
|
11
|
+
error: (error) => console.error(error),
|
|
12
|
+
complete: () => console.log('stopped')
|
|
13
|
+
});
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Handle invoked actor failures with `onError`. Model expected outcomes as events or final outputs. Reserve thrown errors for failures the actor cannot handle locally.
|
|
17
|
+
|
|
18
|
+
Stopping a parent also stops its children.
|
|
19
|
+
|
|
20
|
+
Undeliverable events are dead letters, not errors. A send to a stopped actor or to a missing target (`enq.sendTo(undefined, ...)`, an unknown child id, or `parent` in a root actor) leaves the sender `active` and reports the event through `onRejectedEvent` and a development warning.
|
|
21
|
+
|
|
22
|
+
Async actors receive an abort signal. Callback actors can return a cleanup function. Use both to release network requests, sockets and event listeners when an actor stops.
|
|
23
|
+
|
|
24
|
+
For example:
|
|
25
|
+
|
|
26
|
+
- leaving `uploading` aborts the active upload
|
|
27
|
+
- ending a call stops its media and signaling actors
|
|
28
|
+
|
|
29
|
+
## Error precedence
|
|
30
|
+
|
|
31
|
+
An error thrown by a transition function, an effect, or an invoked or spawned child is resolved by the first step that applies:
|
|
32
|
+
|
|
33
|
+
1. The `onError` of the nearest enclosing active state that handles the error event recovers it. The actor stays `active`, and subscribers do not receive `error`. In a parallel state, a region's `onError` recovers a failure inside that region without exiting sibling regions.
|
|
34
|
+
2. Otherwise the actor's status becomes `'error'` and the actor stops all of its children, invoked and spawned. A child actor also sends `xstate.error.actor` (with `actorId` and `error`) to its parent, which handles it by step 1.
|
|
35
|
+
3. Subscribers with an `error` observer receive the error. A subscriber added after the actor errored receives the same error immediately.
|
|
36
|
+
4. If any subscriber lacks an `error` observer, the error is also reported once to the host's unhandled error channel (`reportUnhandledError`), even when other subscribers receive it in step 3. Passive observers do not count. The report is deferred by one macrotask; subscribing with an `error` observer before then suppresses it.
|
|
37
|
+
|
|
38
|
+
An error thrown by a `subscribe` observer or an `on()` listener is reported as unhandled and does not affect the actor.
|
|
39
|
+
|
|
40
|
+
## Lifecycle cheatsheet
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
const actor = createActor(logic);
|
|
44
|
+
const subscription = actor.subscribe({ next, error, complete });
|
|
45
|
+
actor.start();
|
|
46
|
+
actor.stop();
|
|
47
|
+
subscription.unsubscribe();
|
|
48
|
+
```
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Listen and subscribe to actors
|
|
3
|
+
description: Turn another actor's events and snapshots into events for this machine.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
<!-- enq.listen and enq.subscribeTo behavior from packages/core/src/stateUtils.ts and packages/core/src/transitionActions.ts -->
|
|
7
|
+
|
|
8
|
+
`enq.listen(...)` and `enq.subscribeTo(...)` wire another actor into the current
|
|
9
|
+
machine. Both map what the other actor produces into an event this machine
|
|
10
|
+
handles. Use them in transition, `entry` or `exit` functions.
|
|
11
|
+
|
|
12
|
+
With experimental [pure system transitions](system-transitions.md), register
|
|
13
|
+
the mapper functions in `systemLogic.mappers` so system snapshots store stable
|
|
14
|
+
definition keys and can replay without live subscriptions.
|
|
15
|
+
|
|
16
|
+
Use them for actors this machine does not [invoke](invoke.md): [spawned](spawn.md) children, children passed in through input, or long-lived actors from a [system](systems.md). Invoked actors already have `onDone`, `onError` and `onSnapshot`.
|
|
17
|
+
|
|
18
|
+
## Listening to emitted events
|
|
19
|
+
|
|
20
|
+
`enq.listen(ref, eventType, mapper)` subscribes to the [emitted events](emitted-events.md) of another actor and raises the mapped event on this machine.
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
const uploadsMachine = createMachine({
|
|
24
|
+
initial: 'uploading',
|
|
25
|
+
states: {
|
|
26
|
+
uploading: {
|
|
27
|
+
entry: (_, enq) => {
|
|
28
|
+
const upload = enq.spawn(uploadLogic, { id: 'upload' });
|
|
29
|
+
|
|
30
|
+
enq.listen(upload, 'upload.*', (event) => ({
|
|
31
|
+
type: 'uploadEvent',
|
|
32
|
+
eventType: event.type
|
|
33
|
+
}));
|
|
34
|
+
},
|
|
35
|
+
on: {
|
|
36
|
+
uploadEvent: ({ event }, enq) => {
|
|
37
|
+
enq.log(event.eventType);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`eventType` accepts an exact type, a prefix wildcard such as `'upload.*'`, or `'*'` for every emitted event. Prefix wildcards work here even though [`actor.on(...)`](emitted-events.md) does not support them.
|
|
46
|
+
|
|
47
|
+
The listened-to actor does not have to be spawned here. It can be an invoked child read from `children`, or an actor received through input:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
entry: ({ children }, enq) => {
|
|
51
|
+
enq.listen(children.upload!, 'upload.failed', () => ({ type: 'retry' }));
|
|
52
|
+
};
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Subscribing to snapshots and lifecycle
|
|
56
|
+
|
|
57
|
+
`enq.subscribeTo(ref, mappers)` subscribes to the other actor's snapshot stream. The mappers object accepts `done`, `error` and `snapshot`:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
entry: (_, enq) => {
|
|
61
|
+
const payment = enq.spawn(authorizePayment, { id: 'payment' });
|
|
62
|
+
|
|
63
|
+
enq.subscribeTo(payment, {
|
|
64
|
+
done: (output) => ({ type: 'paymentSucceeded', output }),
|
|
65
|
+
error: (error) => ({ type: 'paymentFailed', error })
|
|
66
|
+
});
|
|
67
|
+
};
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`done` receives the child's output when it reaches `done`. `error` receives the error when it reaches `error`. `snapshot` receives each `active` snapshot, so use it for progress rather than completion.
|
|
71
|
+
|
|
72
|
+
Pass a single function as shorthand for `{ snapshot }`:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
enq.subscribeTo(upload, (snapshot) => ({
|
|
76
|
+
type: 'progress',
|
|
77
|
+
percent: snapshot.context.percent
|
|
78
|
+
}));
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
A subscription created in the same entry action as the spawn starts before the child does, so it also receives the child's initial `active` snapshot. Subscribing to an actor that has already been stopped produces nothing.
|
|
82
|
+
|
|
83
|
+
## Stopping
|
|
84
|
+
|
|
85
|
+
Both functions return an actor reference. Stop it with `enq.stop(...)` to stop listening while leaving the observed actor running.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
entry: ({ context }, enq) => {
|
|
89
|
+
const listener = enq.listen(context.ticker, 'tick', () => ({ type: 'tick' }));
|
|
90
|
+
return { context: { ...context, listener } };
|
|
91
|
+
},
|
|
92
|
+
on: {
|
|
93
|
+
pause: ({ context }, enq) => {
|
|
94
|
+
enq.stop(context.listener);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
> **Warning:** These listeners are actors, not plain callbacks. Keep the returned reference if the machine ever needs to stop the subscription; otherwise it lives until the parent stops.
|
|
100
|
+
|
|
101
|
+
## TypeScript
|
|
102
|
+
|
|
103
|
+
The mapped event must be an event this machine accepts, so mappers are checked against the machine's `schemas.events`. `enq.subscribeTo(...)` infers the output type in `done` and the snapshot type in `snapshot` from the observed actor. `enq.listen(...)` does not infer the emitted event from `eventType`, so annotate the mapper argument when you need the payload typed.
|
|
104
|
+
|
|
105
|
+
## Listen and subscribe cheatsheet
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
// emitted events → machine event
|
|
109
|
+
const listener = enq.listen(ref, 'data.*', (event) => ({
|
|
110
|
+
type: 'dataChanged',
|
|
111
|
+
eventType: event.type
|
|
112
|
+
}));
|
|
113
|
+
|
|
114
|
+
// lifecycle → machine events
|
|
115
|
+
const subscription = enq.subscribeTo(ref, {
|
|
116
|
+
done: (output) => ({ type: 'finished', output }),
|
|
117
|
+
error: (error) => ({ type: 'failed', error }),
|
|
118
|
+
snapshot: (snapshot) => ({ type: 'progress', snapshot })
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// snapshot-only shorthand
|
|
122
|
+
enq.subscribeTo(ref, (snapshot) => ({ type: 'progress', snapshot }));
|
|
123
|
+
|
|
124
|
+
enq.stop(listener);
|
|
125
|
+
enq.stop(subscription);
|
|
126
|
+
```
|