I'm trying to create an interpret for Xstate, and I'm trying to pass it a Machine I had created in a separate file, something like this:
import { Machine } from 'xstate';
const testMachine = Machine({
id: 'testMachine',
initial: 'start',
states: {
start: {
on: {
PUB_TOPIC: 'wait_micro_res',
},
},
wait_micro_res: {
on: {
MACHINE_DISCONNECTED: 'disconnection',
CONFIRMATION_RECEIVED: 'wait_order',
},
},
wait_order: {
on: {
DISCONNECTION_ORDER: 'end',
EXPERIMENT_ORDER: 'wait_measurement',
},
},
wait_measurement: {
on: {
EXPERIMENT_FINISHED: 'end',
MEASUREMENT_RECEIVED: 'receive_measurement',
},
},
receive_measurement: {
on: {
SEND_2_EXPERIMENT_MS: 'wait_measurement',
},
},
disconnection: {
on: {
RECONNECTION: 'wait_micro_res',
},
},
end: {
type: 'final',
},
},
});
export default {
testMachine,
};
I'm trying to create it this way:
import { interpret } from 'xstate/lib/interpreter';
import testMachine from '../stateMachine/index';
const machineService = interpret(testMachine)
.onTransition((state) => {
console.log(state.value);
})
.start();
However I'm getting this error:
TypeError: Cannot set property '_sessionid' of undefined
When I try to create the machine in the same file of the interpreter all runs fine. I tried to log the machine and it seems to be imported correctly, but I don't know if there's an additional mistake I'm not aware about
There seems to be a problem with your export. You are exporting { testMachine }
as the default export instead of testMachine
.
You should use:
export default testMachine;
Then when you import testMachine from '../stateMachine/index';
you will get the desired object.
For now you are importing an object with a property testMachine
that contains you machine.
If you want to keep that export, use:
const machineService = interpret(testMachine.testMachine)