How do I add a computed property in a child class?
This is the code I have:
import {
get,
makeObservable,
extendObservable,
observable,
computed
} from "mobx";
class Base {
x = 123;
constructor() {
makeObservable(this, { x: observable });
}
}
class Child extends Base {
constructor() {
super();
extendObservable(this, { x2: computed });
}
get x2() {
return this.x * this.x;
}
}
const child = new Child();
console.log("child.x2=", child.x2);
console.log("get (child.x2)=", get(child, "x2"));
The output is:
child.x2= ƒ Child@61.x2() {}
get (child.x2)= ƒ Child@61.x2() {}
But I expected to see a number returned by my getter.
Moving get x2
to the base class and decorating it with computed
there works fine, but it doesn't fit my application logic.
Citing the docs:
extendObservable
Can be used to introduce new properties on the target object and make them observable immediately. Basically a shorthand for Object.assign(target, properties); makeAutoObservable(target, overrides, options);. However, existing properties on target won't be touched.
So I guess you cannot use it for existing property, you either need to remove it from the class and inline pass it directly to extendObservable
call or use another makeObservable
call instead.