@xstate/react feature request: trigger predifined events before stopping the interpreted service #1507
-
Hello 👋 Thanks for the cool libraries! State Machines for the win! 🎉 Got a feature request for the @xstate/react and useMachine hook. What? Why? Why again? On component unmount, I want to close connection, that my machine manages, but Here's some code sandbox example in a nutshell ...
import { myCoolMachine } from './myCoolFile'
const CoolConnectionState = () => {
const [state, send, service] = useMachine(myCoolConnectionMachine)
useEffect(() => {
send('CONNECT')
return () => send('DISCONNECT') // doesn't work, cause machine is stopped already by useMachine
}, [send]) //send shouldn't change
return <div>{state.value}</div>
} Request |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
That should be an implementation detail, no? For instance, if you are invoking an actor, you should specify the disposal there: // example
// ...
{
invoke: {
src: (context, event) => (sendBack) => {
// ...
// disposal
return () => {
// do proper disposal here
}
}
}
} And when the service is stopped ( |
Beta Was this translation helpful? Give feedback.
-
Keep in mind that React actively discourages thinking in terms of mount/unmount - their model is synchronization to the state. If you absolutely need this (but usually you really shouldn't) then you can just reorder things: let state, send
useEffect(() => {
send("CONNECT");
return () => send("DISCONNECT");
}, []);
;([state, send] = useMachine(connectionMachine)); But as @davidkpiano said - you probably should make this an invoked service and have it managed for you. |
Beta Was this translation helpful? Give feedback.
That should be an implementation detail, no?
For instance, if you are invoking an actor, you should specify the disposal there:
And when the service is stopped (
service.stop()
as you've mentioned) it will properly stop the invoked service.