xaviergonz / mobx-keystone

A MobX powered state management solution based on data trees with first class support for Typescript, support for snapshots, patches and much more
https://mobx-keystone.js.org
MIT License
549 stars 25 forks source link

Submodel type check error #309

Open hersentino opened 3 years ago

hersentino commented 3 years ago

Hello,

I would like to create model from json api response, however, I get typeCheckError when loading a submodel (b in the sample below)

If I change tProp to prop for b in A it works. However I would to use type runtime checking. How to solve this error ?

Thanks for your lib :)

class B extends Model({ name: tProp(types.string)}) {}

class A extends Model({ name: tProp(types.string), b: tProp(types.model(B)) }) {}

const a = new A({ name: "foo", b: { name: "bar" } })
sisp commented 3 years ago

You need to create the instance of B explicitly:

const a = new A({ name: "foo", b: new B({ name: "bar" }) })
hersentino commented 3 years ago

I would like to create it FROM json, not to parse everything by converting api model to mobx model. I would like to do it for transparent conversion. In mobx-state-tree it’s working, we can create instances with submodule from json

dodas commented 3 years ago

@hersentino If you are getting a mobx-keystone "snapshot" of A from server (that means all models have $modelType prop), then you can call fromSnapshot() rather than new A(), and all nested models would get initialized automatically.

sxwebdev commented 3 years ago

I would like to create it FROM json, not to parse everything by converting api model to mobx model. I would like to do it for transparent conversion. In mobx-state-tree it’s working, we can create instances with submodule from json

Hi. I faced the same problem. There are many nested models in my model. The data comes from the server in json format. How to efficiently convert a json to a mobx-keystone model? It's problematic for me to create an instance for each nested model, and then collect it into a general one. Snapshot copies are not stored on the server.

Thanks

xaviergonz commented 3 years ago

@sxwebdev if you cannot store $modelType in the snapshot, nor want to do the manual conversion, would you be ok using either frozen (https://mobx-keystone.js.org/frozen) or data models (https://mobx-keystone.js.org/dataModels) ?