Skip to content

Commit 7fb2371

Browse files
committed
Add Events Stop Propagating Once Handled as an XState til
1 parent c5acd10 commit 7fb2371

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1142 TILs and counting..._
13+
_1143 TILs and counting..._
1414

1515
---
1616

@@ -1336,6 +1336,7 @@ _1142 TILs and counting..._
13361336
### XState
13371337

13381338
- [Define Event That Does Internal Self Transition](xstate/define-event-that-does-internal-self-transition.md)
1339+
- [Events Stop Propagating Once Handled](xstate/events-stop-propagating-once-handled.md)
13391340
- [Inline Actions vs Actions In Machine Options](xstate/inline-actions-vs-actions-in-machine-options.md)
13401341
- [Simple States And Composite States](xstate/simple-states-and-composite-states.md)
13411342
- [Use An XState Machine With React](xstate/use-an-xstate-machine-with-react.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Events Stop Propagating Once Handled
2+
3+
In a hierarchical (or nested) XState machine, events are sent to the inner most sub-state of
4+
the current state. If that state handles the event, then it won't propagate up
5+
to parent states. If a state receives an event that it doesn't handle, that
6+
event will propagate up to parent states until it is handled or there is
7+
nothing to handle it.
8+
9+
Let's look at an example.
10+
11+
```javascript
12+
{
13+
initial: "active",
14+
context: { count: 0 },
15+
states: {
16+
active: {
17+
on: {
18+
COUNT: {
19+
actions: "changeCount",
20+
},
21+
},
22+
initial: "increment",
23+
states: {
24+
increment: {
25+
on: {
26+
SWITCH_COUNT_DIRECTION: "decrement",
27+
},
28+
},
29+
decrement: {
30+
on: {
31+
SWITCH_COUNT_DIRECTION: "increment",
32+
COUNT: {
33+
actions: 'logEvent'
34+
},
35+
},
36+
},
37+
},
38+
},
39+
},
40+
};
41+
```
42+
43+
This machine starts in the `active.increment` state.
44+
45+
If I send the `COUNT` event, it will first go to the `active.increment` state.
46+
It isn't handled there, so it will propagate up to `active` where it is
47+
handled.
48+
49+
Now let's say I transition to `active.decrement`. If I send the `COUNT` event,
50+
it will first go to `active.decrement` where it is handled. The `logEvent`
51+
action happens and then the event stops. The `active` state does not receive
52+
nor handle the `COUNT` event.
53+
54+
[source](https://twitter.com/jbrancha/status/1418269852398129152?s=20)

0 commit comments

Comments
 (0)