Serializing MST Document in Creative Tool #1925
|
I am making a diagramming tool and assumed MST would allow me to serialize/deserialize my whole app or document state. But it seems it doesn't include type information in getSnapshot(), so when I pass the serialized json created by getSnapshot() to applySnapshot elements that have compound types like (Rectangle|Oval|PenStrokes) aren't reinstated. What am I missing? Searched around for an hour and didn't find anything. Should I be rolling my own serialize/deserialize and create my own type fields? |
Replies: 4 comments
|
Hi @seflless! Do you think you could create a minimal reproducible example in e.g. CodeSandbox? I don't quite understand exactly what's going wrong. |
|
Hi Emil, Basically I'd hope for a library that allows this:
Codesandbox ExampleI'm hoping this Codesandbox helps explain my confusion: https://codesandbox.io/s/mobx-state-tree-test-hdkq15?file=/src/Models.js. The part in particular that just isn't what I expect is that it seems that there is no information saved that specifies what type things are, so how can it possibly reinstate a model instance. In this example you can see that I create a document type that can add a union that has a Rectangle and Oval, but when I restore it. The Oval instance is restored as a Rectangle. Does that make sense? |
|
Great, thank you for the extensive example @seflless . The
You could e.g. check if the snapshot has a const Shape = types.union(
{ dispatcher: (snapshot) => 'radius' in snapshot ? Circle : Rectangle },
Rectangle,
Circle
); |
|
Perfect, thank you, that fixed it! |
Great, thank you for the extensive example @seflless .
The
Utility typesdocumentation states in passing that:You could e.g. check if the snapshot has a
radiusand instantiate it as aCircle, otherwise aRectangle.