The actor transitions to the complete state as soon as it starts(updated) #5159
-
Hello, I’ve been interested in XState since version 4, and I’m currently studying and testing it while going through the documentation. However, there are some parts I don’t fully understand, so I wanted to ask a question. I’m trying to test Am I doing something wrong? import * as React from "react";
import { AnyMachineSnapshot, createActor, createMachine, setup } from "xstate";
const machine = setup({
types: {
events: {} as { type: "trigger_error" },
context: {} as {
hello: string;
},
},
actions: {
triggerError: () => {
throw new Error("Throw Error!!");
},
},
}).createMachine({
id: "testing",
context: {
hello: "there",
},
initial: "idle",
states: {
idle: {},
error: {},
},
on: {
trigger_error: {
actions: "triggerError",
},
},
});
function App() {
const [actor] = React.useMemo(() => {
const _machine = createMachine(machine.config, machine.implementations);
return [createActor(_machine as any)];
}, []);
const [actorSnapshot, setActorSnapshot] = React.useState<AnyMachineSnapshot>(
actor.getSnapshot()
);
React.useEffect(() => {
const { unsubscribe } = actor.subscribe({
next: (snapshot) => {
console.log("onNext", snapshot);
setActorSnapshot(snapshot);
},
error: (error) => {
console.error("Maybe because it's a completed machine, this code doesn't seem to work."); // <-- not printed
console.error("onError", error);
},
complete: () => {
console.log("Why does this message get printed right at the start?"); // <-- printed when it starts.
console.log("onComplete");
},
});
actor.start();
return () => {
unsubscribe();
actor.stop();
};
}, [actor]);
const handleClick = () => {
actor.send({
type: "trigger_error",
});
};
return (
<div className="App">
<pre>{JSON.stringify(actorSnapshot, null, 2)}</pre>
<button onClick={handleClick}>Trigger Error</button>
</div>
);
}
export default App; https://codesandbox.io/p/devbox/xstate5-actor-subscribe-2mfdgc?embed=1&showConsole=true |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I suspect this is due to a stale closure. Can you try this in a vanilla JS context instead of in React? |
Beta Was this translation helpful? Give feedback.
I suspect this is due to a stale closure. Can you try this in a vanilla JS context instead of in React?