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

Only use "prop" with primitive values and never with object values #3

Closed sisp closed 5 years ago

sisp commented 5 years ago

The documentation of props states:

https://github.com/xaviergonz/mobx-keystone/blob/1f375e5520b2aae291ca6e99f4e1ecbbc44d498c/packages/lib/src/model/prop.ts#L63-L64

But in the "Flows (async actions)" section of the docs, the book store example has a prop<Book[]>(() => []) prop:

@model("myApp/Auth")
class BookStore extends Model({
  books: prop<Book[]>(() => []),
}) {
  // ...
}

Are non-primitive types in prop in fact allowed and if not, how should a non-primitive prop be declared, e.g. a nested object prop for which I don't want to define a separate class/model?

xaviergonz commented 5 years ago

The "this" in the docs refers to the non lambda initializer. This is, primitives can be initialized with or without lambdas, but non primitives have to use the lambda always. (guess I should make the docs more clear)

sisp commented 5 years ago

Ah, now that you're saying it like this, I double-checked and it is stated in the docs - I didn't read it properly.

Without runtime type checking:

  • prop<T>() - A property of a given type, with no default set if it is undefined in the initial data.
  • prop<T>(defaultValue: T) - A property of a given type, with a default set if it is undefined in the initial data. Use this only for default primitives.
  • prop<T>(defaultFn: () => T) - A property of a given type, with a default value generator if it is undefined in the initial data. Usually used for default objects / arrays / models.

Sorry, my fault.