[Feature Request] Inherit actions from parent state, or global actions #1360
-
Hi, I'm introduced to this amazing library recently, and I immediately started to see the great benefit of it in one of my projects, thanks very much! Yesterday I find it impossible to declare something like In other words, instead of something like this: const machine = Machine({
states: {
s1: {E1: {target: s2, actions: A1},
s2: {E1: {target: s3, actions: A1},
s3: {E1: {target: s4, actions: A1},
}
}); My goal is to replace it with something like: const machine = Machine({
globalActions: {E1: A1},
states: {
s1: {E1: s2},
s2: {E1: s3},
s3: {E1: s4},
}
}); I tried to implement this as an
E.g. this doesn't work: const machine = Machine({
states: {
s1: {E1: {target: s2, actions: A1},
s2: {after: [{
delay: {timestamp} => calculateDelay(timestamp),
target: s3
}]
},
s3: {E1: {target: s1, actions: A1},
}
}, {
actions: {
A1: assigner({timestamp: context => updateTimestamp(context)})
}
}); Because the So my question is: am I missing something that could be used to achieve this |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
It's not supported in XState because it's not supported in SCXML. There is an idea explored by Harel in his original paper called "clustering" which addresses this, but that idea was scrapped because of its complexity/ambiguity. Anyway, there's a couple of ways to solve this. You can be more explicit and have two types of events; for example:
So if you think of the logic in plain terms, you can phrase it this way:
That second part can be the responsibility of that const A1 = () => console.log('Action A1');
const machine = Machine({
initial: 's1',
states: {
h: { type: 'history' },
s1: {on: {E11: 's2'}},
s2: {on: {E11: 's3'}},
s3: {on: {E11: 's4'}},
s4: {/* ... */}
},
on: {
E1: {
target: 'h',
actions: [A1, send('E11')]
}
}
}); A machine sending itself events is a powerful technique, and it's how most embedded electronics work (which use state machines/statecharts extensively!). |
Beta Was this translation helpful? Give feedback.
-
This definitely a genius & elegant idea, thanks for the swift help @davidkpiano ! |
Beta Was this translation helpful? Give feedback.
It's not supported in XState because it's not supported in SCXML. There is an idea explored by Harel in his original paper called "clustering" which addresses this, but that idea was scrapped because of its complexity/ambiguity.
Anyway, there's a couple of ways to solve this. You can be more explicit and have two types of events; for example:
E1
can be for executingA1
E11
can be for transitioning between statesSo if you think of the logic in plain terms, you can phrase it this way:
That second part can be the responsibility of that
E11
event. A machine can send itself events, so: