I'm working on a UI project which handles state updates through a shared context, very similar as described here
const {appState, dispatch} = useContext(AppContext);
I'm not toying around with state machines through xstate for some of the components.
const SomeComponent = () => {
const {appState, dispatch} = useContext(AppContext);
const [state,send,service] = useMachine(MyComponentStateMachine);
}
Now, ideally I would like my state machine to dispatch certain events when entering a state. What's the best way for the state machine to get a hold of my AppContext, though?
At the moment, I'm handling this event dispatching on the component itself, observing the state of the state machine and dispatching an event as needed when it enters a certain state:
const SomeComponent = () => {
const {appState, dispatch} = useContext(AppContext);
const [state,send,service] = useMachine(MyComponentStateMachine);
useEffect(() => service.subscribe(state => {
if(state.value == "Some relevant state of MyComponentStateMachine")
dispatch({type: SomeEvent, arg: 12345});
}).unsubscribe, [service]);
}
This works well, but it strikes me as bad design. I'd think it would be cleaner to dispatch this event from the state machine directly, rather than from the component.
Is there any good way for the state machine to get a hold of AppContext?
Would it be sensible to simply create a factory method for the state machine which takes dispatch as an argument, and holds on to it?
question from:
https://stackoverflow.com/questions/65831389/combine-usemachine-with-usecontext 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…