1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Make Immediate And Delayed Transitions as an xstate til

This commit is contained in:
jbranchaud
2021-08-26 11:57:10 -05:00
parent 94ade71d40
commit 0b8111e1ee
2 changed files with 50 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_1148 TILs and counting..._
_1149 TILs and counting..._
---
@@ -1343,6 +1343,7 @@ _1148 TILs and counting..._
- [Define Event That Does Internal Self Transition](xstate/define-event-that-does-internal-self-transition.md)
- [Events Stop Propagating Once Handled](xstate/events-stop-propagating-once-handled.md)
- [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)
- [Use An XState Machine With React](xstate/use-an-xstate-machine-with-react.md)

View File

@@ -0,0 +1,48 @@
# Make Immediate And Delayed Transitions
An [XState](https://xstate.js.org/docs/) state can define an `on` key with an
object. The object can define one or more events that the state listens for and
transitions in response to. In addition to transitioning in response to an
event, you can have a state do both _immediate_ and _delayed_ transitions.
Here is an example state machine.
```javascript
export const loadingSpinner = createMachine(
{
initial: 'pending',
context: {},
states: {
pending: {
always: [
{ target: 'loading' }
]
},
loading: {
after: {
5000: { target: 'done' }
}
},
done: {
final: true
}
}
}
);
```
This machine will start in the `pending` state. The `always` object will
immediately fire which will trigger a transition to the `loading` state. There
the `after` object will schedule a transition to the `done` state to happen in
5 seconds (5000ms).
The
[`always`](https://xstate.js.org/docs/guides/transitions.html#eventless-always-transitions)
is the immediate transition. The
[`after`](https://xstate.js.org/docs/guides/delays.html#delayed-transitions) is
the delayed transition.
The "eventless" `always` transition, in practice, is more useful when combined
with a condition. That allows you to define an immediate transition that only
takes place if some condition has already been met (e.g. does the `context`
already contain the thing we were about to look up?).