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

Add Events Stop Propagating Once Handled as an XState til

This commit is contained in:
jbranchaud
2021-07-22 20:12:24 -05:00
parent c5acd10b3a
commit 7fb2371a81
2 changed files with 56 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).
_1142 TILs and counting..._
_1143 TILs and counting..._
---
@@ -1336,6 +1336,7 @@ _1142 TILs and counting..._
### XState
- [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)
- [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,54 @@
# Events Stop Propagating Once Handled
In a hierarchical (or nested) XState machine, events are sent to the inner most sub-state of
the current state. If that state handles the event, then it won't propagate up
to parent states. If a state receives an event that it doesn't handle, that
event will propagate up to parent states until it is handled or there is
nothing to handle it.
Let's look at an example.
```javascript
{
initial: "active",
context: { count: 0 },
states: {
active: {
on: {
COUNT: {
actions: "changeCount",
},
},
initial: "increment",
states: {
increment: {
on: {
SWITCH_COUNT_DIRECTION: "decrement",
},
},
decrement: {
on: {
SWITCH_COUNT_DIRECTION: "increment",
COUNT: {
actions: 'logEvent'
},
},
},
},
},
},
};
```
This machine starts in the `active.increment` state.
If I send the `COUNT` event, it will first go to the `active.increment` state.
It isn't handled there, so it will propagate up to `active` where it is
handled.
Now let's say I transition to `active.decrement`. If I send the `COUNT` event,
it will first go to `active.decrement` where it is handled. The `logEvent`
action happens and then the event stops. The `active` state does not receive
nor handle the `COUNT` event.
[source](https://twitter.com/jbrancha/status/1418269852398129152?s=20)