xstate/fsm - Ability to get most recent event in callback/state object #1352
Unanswered
timothyallan
asked this question in
General
Replies: 1 comment
-
|
Option 1 — Store event in context (formalized): import { createMachine, assign, interpret } from '@xstate/fsm';
const machine = createMachine({
initial: 'idle',
context: { lastEvent: null as string | null },
states: {
idle: {
on: {
FETCH: {
target: 'loading',
actions: [assign({ lastEvent: (_ctx, event) => event.type })],
},
},
},
loading: {
on: {
SUCCESS: {
target: 'idle',
actions: [assign({ lastEvent: (_ctx, event) => event.type })],
},
FAIL: {
target: 'idle',
actions: [assign({ lastEvent: (_ctx, event) => event.type })],
},
},
},
},
});
const service = interpret(machine).start();
service.subscribe((state) => {
console.log('State:', state.value, '| Last event:', state.context.lastEvent);
});
service.send('FETCH');
// State: loading | Last event: FETCHOption 2 — Wrap let lastEvent: string | null = null;
const _send = service.send.bind(service);
service.send = (event) => {
lastEvent = typeof event === 'string' ? event : event.type;
return _send(event);
};
service.subscribe((state) => {
console.log(state.value, lastEvent);
});Option 3 — Use full Full service.onTransition((state) => {
console.log('Triggered by:', state.event.type);
});
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I really want to use xstate/fsm as I don't need any of the bigger xstate features. However, I do need to know when an event is fired, not just a state changed. Right now I'm looking at making an 'event' field in the context and populating it on each event.
It'd sure be nice to have something like xstates
onTransitionwhich brings back the state + the event in the listener, a field in the state itself, or at least some way to see what the event was.Beta Was this translation helpful? Give feedback.
All reactions