diff --git a/README.md b/README.md index e99f4f9..42f84dc 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1158 TILs and counting..._ +_1159 TILs and counting..._ --- @@ -1358,6 +1358,7 @@ _1158 TILs and counting..._ - [Inline Actions vs Actions In Machine Options](xstate/inline-actions-vs-actions-in-machine-options.md) - [Make Immediate And Delayed Transitions](xstate/make-immediate-and-delayed-transitions.md) - [Simple States And Composite States](xstate/simple-states-and-composite-states.md) +- [Start A Machine In A Specific State](xstate/start-a-machine-in-a-specific-state.md) - [Use An XState Machine With React](xstate/use-an-xstate-machine-with-react.md) ### YAML diff --git a/xstate/start-a-machine-in-a-specific-state.md b/xstate/start-a-machine-in-a-specific-state.md new file mode 100644 index 0000000..b340b3e --- /dev/null +++ b/xstate/start-a-machine-in-a-specific-state.md @@ -0,0 +1,37 @@ +# Start A Machine In A Specific State + +For testing (or debugging) purposes, it can be handy to get an XState machine +running from a specific state. + +Let's say a machine has an initial state of `green` and the other states it can +be in are `yellow` and `red`. And `yellow` has sub-states of `walk` and +`hurry`. + +By default, a machine will start in the specified initial state. + +```javascript +const service = interpret(trafficLightMachine); + +service.start(); + +service.state.value; //=> 'green' +``` + +We can tell the traffic light service to start in the `red` state instead. + +```javascript +service.start('red'); + +service.state.value; //=> 'red' +``` + +We can even tell it to start in a sub-state (nested state) of a particular +state. + +```javascript +service.start({ yellow: 'hurry' }); + +service.state.value; //=> { yellow: 'hurry' } +``` + +[source](https://xstate.js.org/docs/guides/interpretation.html#starting-and-stopping)