How to determine if a state has been entered using an interpreter? #3567
-
Let’s assume I want to trigger an side effect every time a specific state is entered. But, I don’t want to do it from within the machine. Instead I want to do it using the service returned by My first attempt looked like this: service.onTransition((state) => {
if (state.changed) {
if (state.matches('foo.bar.baz')) {
triggerSideEffect();
}
}
}); but that obviously doesn’t work, because it gets executed on any transition where I though about a couple of approaches but none of them are available in xstate right now: Having access to service.onTransition((state, previousState) => {
if (state.changed) {
if (state.matches('foo.bar.baz') && !previousState.matches('foo.bar.baz')) {
triggerSideEffect();
}
}
}); Introduce new state method service.onTransition((state) => {
if (state.changed) {
if (state.hasEntered('foo.bar.baz')) {
triggerSideEffect();
}
}
}); Introduce new service method service.onEntry('foo.bar.baz', (state) => {
triggerSideEffect();
}); Is something similar already possible today? If not, do you think it would be good idea to add something like that to the xtate interpreter? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The way you would do it, following the algorithm that XState itself uses, is that you would compare the previous let prevStateNodes;
service.subscribe(state => {
if (state.configuration.find(stateNode => stateNode.id === 'some.state.id' && !prevStateNodes?.includes(stateNode))) {
// state was entered
}
prevStateNodes = state.configuration;
}); |
Beta Was this translation helpful? Give feedback.
The way you would do it, following the algorithm that XState itself uses, is that you would compare the previous
state.configuration
to the currentstate.configuration
: