I am new to xstate, and I'm trying to use it in an application where a user can request different things in an application, based on parent state and/or sub-state. However, there are some requests that the user should be able to make, no matter what state/sub-state the app is in. The response to those events is the same, no matter what the previous state was. How can I configure this event, so that I don't have to repeat define it under all states/sub-states?
Asked
Active
Viewed 1,904 times
1 Answers
6
Yes - the algorithm for choosing transitions is similar to DOM event propagation, in that it searches from leaf nodes to root node.
You can define transitions on the root node (top-level) which will be handled in any state naturally:
import { createMachine } from 'xstate';
const machine = createMachine({
// ...
// top-level transitions
on: {
ESC: {/* ... */}
},
states: {
// ...
someState: {
on: {
ESC: {/* override top-level transition */}
}
}
}
});

David Khourshid
- 4,918
- 1
- 11
- 10
-
Oh that's perfect, exactly what I needed! – curiousWebDev Apr 24 '20 at 19:49
-
sorry for offtop, i'm looking for an opposite behaviour, in DOM words - bubbling the event up to the root node (and execute the actions on all states were the event is defined ). is it possible with xstate? – Valentin Kantor Jul 19 '21 at 17:33
-
1@ValentinKantor This is not possible with the algorithm (which follows the SCXML algorithm). – David Khourshid Jul 20 '21 at 23:32