#Persist machine with spawned child

1 messages · Page 1 of 1 (latest)

swift scarab
#

Hey, I'm trying to use the actor.getPersistedSnapshot() function to store the state of a machine that spawned a child machine. Before the spawning, the persisted snapshot works. But as soon as the transition where the spawning happens is executed, the function does not work anymore. Does anyone have an idea what the problem is or what I'm doing wrong? Thanks 🙂

This is the machine:

.createMachine({
  context: ({spawn}) => ({
    aneSpawn: undefined,
    prepSpawn: undefined,
    indSpawn: undefined,
  }),
  id: "main",
  initial: "start",
  states: {
    start: {
      on: {
        addAne: {
          actions: assign({aneSpawn: ({spawn}) => spawn(anesthesiaMachine, {systemId: 'aneSpawned', syncSnapshot: true})}),
          target: "anesthesiaSpawned",
        },
        addPrep: {
          actions: assign({prepSpawn: ({spawn}) => spawn(preparationMachine, {systemId: 'prepSpawned', syncSnapshot: true})}),
          target: "preparationSpawned"
        }
      },
      description: "P1_start description",
    },
    anesthesiaSpawned: {
      on: {
        addPrep: {
          actions: assign({prepSpawn: ({spawn}) => spawn(preparationMachine, {systemId: 'prepSpawned', syncSnapshot: true})}),
          target: "spawned"
        }}
    },
    preparationSpawned: {
      on: {
        addAne: {
          actions: assign({aneSpawn: ({spawn}) => spawn(anesthesiaMachine, {systemId: 'aneSpawned', syncSnapshot: true})}),
          target: "spawned"
        }}
    },
  },
});

Here I'm trying to store:

function App() {
  const [child, setChild] = useState("");
  const actor = createActor(mainMachine, {inspect: inspect});
  actor.start();
  return (
    <div className="App">
      <button onClick={() => actor.send({type: 'addPrep'})}>
        addPrep
      </button>
      <button onClick={() => setChild(JSON.stringify(actor.getPersistedSnapshot()))}>
        snap
      </button>
      <br/>
      <label>
        {child}
      </label>
    </div>
  );
}
#

Edit: Whenever I click the button to make the snapshot, 2 new actors appear in the Stately Inspector. Could that have something to do with the problem? And how can I prevent that?

crisp narwhal
#

Also, in the code, you should not create an actor directly in the component - that may be what's causing issues

#
const actor = useActorRef(mainMachine, …)
// no need to start it