In xstate v4 it used to be possible to listen for a service's onDone
event by doing the following:
const [state, send, service] = useMachine(fsm)
useEffect(() => {
const listener = () => {
props.submit(state.context) // or similar
};
service.onDone(listener);
return () => { service.off(listener) }
}, [service, props.submit]);
However in xstate v5, useMachine
returns an ActorRef
rather than a Service
, and ActorRef
does not have an onDone
function.
Is there any way to listen for final states using idiomatic React, or do we need to pass the action to the machine as described here?
Yes, use an observer:
const [state, send, actor] = useMachine(fsm);
useEffect(() => {
const sub = actor.subscribe({
complete: () => {/* ... */}
});
return sub.unsubscribe;
}, [actor]);