From 7fb2371a811763950dcfb522ec458afcbe697ba5 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 22 Jul 2021 20:12:24 -0500 Subject: [PATCH] Add Events Stop Propagating Once Handled as an XState til --- README.md | 3 +- .../events-stop-propagating-once-handled.md | 54 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 xstate/events-stop-propagating-once-handled.md diff --git a/README.md b/README.md index 5b899b5..7470d20 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://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) diff --git a/xstate/events-stop-propagating-once-handled.md b/xstate/events-stop-propagating-once-handled.md new file mode 100644 index 0000000..e5a69c7 --- /dev/null +++ b/xstate/events-stop-propagating-once-handled.md @@ -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)