Given the folloowing code:
class Jedi {
@observable firstName = "";
@observable lastName = "";
constructor(options) {
extendObservable(this, options);
}
}
If options
has firstName
and lastName
, the result will be that firstName
and lastName
will be "" (the default defined above) not the values found in options.
I know that the following code was working before the update (it was in our codebase):
class Silly {
@observable thing = observable(true);
}
That code no longer works in MobX 4.0.0. It's a little silly but easy to fix. However, I believe this is what is happening under the hood when you use extendObservable()
to set fields that are already defined as observable.
class Jedi {
// don't define firstName/lastName here
constructor(options) {
extendObservable(this, options);
}
}
class Jedi {
@observable firstName = "";
@observable lastName = "";
constructor({ firstName, lastName }) {
this.firstName = firstName;
this.lastName = lastName;
}
}
class Jedi {
@observable firstName = "";
@observable lastName = "";
constructor(options) {
// write/find a util function that sets all observable properties on the class
// ignoring options that are not defined on the class or are computeds/actions/functions
initializeObservable(this, options);
}
}
class DimensionsById {
constructor(dimensions) {
const idMap = {};
dimensions.forEach(dim => idMap[dim.id] = dim);
// we don't know what the fields are going to be until runtime
// so lets use extendObservable!
extendObservable(idMap);
}
}