How do I deserialize a serialized machine? #4785
-
XState Version: 5.9.1 Aloha folks, How do I deserialize a machine from JSON back into a usable machine? My first attempt (simply JSON parsing the JSONified output of $ node
Welcome to Node.js v20.9.0.
Type ".help" for more information.
> const { createActor, setup } = require('xstate');
> var config = {
id: 'le machine',
initial: 'Start',
states: { Start: { on: { end: 'End' } }, End: { on: { start: 'Start' } } },
};
> createActor(setup({}).createMachine(config)).start(); // works as expected
// undefined
> var serializedMachine = JSON.stringify(createMachine(config).toJSON());
> var deserializedMachine = JSON.parse(serializedMachine);
> createActor(setup({}).createMachine(deserializedMachine)).start(); // dies horribly
// Uncaught:
// Error: Initial state node "[object Object]" not found on parent state node #le machine
// ...<stack trace> I don't see any dedicated API methods catering to restoring serialized machines, so I presume I'm either missing something obvious, or it's not possible. I don't have a concrete use-case for this yet by the way, just vague ideas; I simply thought it ought to be possible, otherwise the only obvious use-case for the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey, you're right; it is possible. Apologies for the lack of documentation on this. You should stringify |
Beta Was this translation helpful? Give feedback.
Hey, you're right; it is possible. Apologies for the lack of documentation on this.
You should stringify
machine.config
instead ofmachine.toJSON()
.