Repository navigation
Is possible to have an "event interceptor"? #5450
Replies: 2 comments 2 replies
I'm not sure I fully understand your requirements 🤔 When transitioning to |
|
Building on rothsandro's question, since I think the "interceptor" framing is what's making this feel like it needs a special mechanism, it doesn't, this is a standard job for guarded transitions, XState just evaluates candidate transitions on the same event in order and picks the first whose guard passes. Rather than one states: {
validating: {
on: {
FRAMES_RECEIVED: [
{
guard: 'isFrameValid',
actions: assign({ /* update context from the frame */ }),
target: 'processing',
},
{
// falls through here when the frame fails validation
target: 'detecting',
},
],
},
},
// processing, done, etc. can declare the same FRAMES_RECEIVED array
// if a stale/invalid frame arriving mid-processing should also restart
}Since the guard re-runs on every If the same validation applies identically across several states, you don't have to repeat the array everywhere, XState supports declaring shared This is standard FSM design, not an XState-specific workaround, guards are meant to be the mechanism for "this event needs different outcomes depending on data in the event/context," which is exactly your case. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I'm creating a machine that constantly receives frames at
FRAMES_RECEIVEDevent and I have four states:detecting,validating,processing,done.detectingandvalidatingtakes the frame and assign values, based on custom logic, to context, that I use in other events.The "problem" is that these validations refer to the frame received in that moment. When the machine reaches a new state, it will have already another frame that needs to go through these validations to proceed; otherwise the flow must be restarted.
It would be nice if I could create an interceptor for this event that perform these validations before reaching the handler of the state, then I could redirect the machine to the initial state based on certain condition.
This is my first time working with FSM and XState, and although I've been studying it all week, I'm not sure if this idea makes sense for an FSM, but I'm really enjoying XState and would appreciate some help with it.
Thanks in advance.
All reactions