How to use default constructor for nested model #1908
Answered
by
EmilTholin
davetapley
asked this question in
Q&A
-
If I have an const Thing = types.model({idx: types.identifier});
const Store = types.model({things: types.array(Thing)})
const store = Store.create(); But if I have a parent object: const Thing = types.model({idx: types.identifier});
const Store = types.model({things: types.array(Thing)})
const Root = types.model({thingStore: Store})
const root = Root.create();
// Error while converting `{}` to `AnonymousModel` I can fix with: Root.create({ thingStore: {} }); But it would be nice if the the default empty constructor would be invoked automatically. Am I missing something? 🤔 |
Beta Was this translation helpful? Give feedback.
Answered by
EmilTholin
May 14, 2022
Replies: 1 comment 1 reply
-
Hi @davetapley! As the You have to explicitly set it to const Thing = types.model({ idx: types.identifier });
const Store = types.model({ things: types.array(Thing) });
const Root = types.model({ thingStore: types.optional(Store, {}) });
const root = Root.create();
// Success! |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
davetapley
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @davetapley!
As the
Miscellaneous Tips
part of the documenatation statestypes.array(Thing)
is the same thing astypes.optional(types.array(Thing), [])
, but that's not the case fortypes.model
.You have to explicitly set it to
types.optional(Store, {})
for it to work the way you would like: