Reputation: 443
I am trying to listen to a value changes with mobx
computed expression, but I don't see any changes when I push a new value to the observed expression.
class List {
@observable values = [];
constructor() {
computed(() => this.values).observe(changes => {
console.log(changes);
})
}
add(item) {
this.values.push(Math.random());
}
}
const list = new List();
list.add();
Why doesn't it work?
Upvotes: 3
Views: 2512
Reputation: 4978
Note that computed
will only track data it actually accesses. The only data accessed in your computed is the changes
, a pointer to an array. Pushing a new value to that array will not change the pointer.
Remember: computeds produce values, reactions & autoruns produce side effects.
Your computed never produces a new value, so never triggers the observer
.
Upvotes: 2
Reputation: 112777
computed is used when you want to derive a new value from other observables. You could use observe instead:
Example (JSBin)
class List {
@observable values = [];
constructor() {
observe(this.values, (change) => {
if (change.added) {
console.log(`${change.added} got added to values`);
}
});
}
add(item) {
this.values.push(Math.random());
}
}
const list = new List();
setInterval(() => {
list.add();
}, 1000);
Upvotes: 0