I'm currently delving into the concept of deep observability in MobX. I'm looking for insights on why the autorun function is not being triggered every time I call setCommentCountForPost in the code snippet below.
Can someone point me in the right direction to rectify this issue? Also, does making a property of Post observable suffice to activate the autorun when accessing the list where the post resides (as shown in the autorun)?
The version of MobX being used is 5.
Edit: I found that the code functions correctly if I include console.log(toJS(p.getPosts())) inside the autorun. While this is intriguing, I'm curious about why this works and how I can achieve the same outcome by only calling getPosts().
Here's the code:
import { useStrict, configure, autorun } from 'mobx';
import { toJS, observable, action, computed } from 'mobx';
configure({ enforceActions: true });
class Post {
@observable commentCount = 0;
setCommentCount(c) {
this.commentCount = c;
}
}
class PostList {
@observable _posts = {};
@action createPost(id) {
this._posts[id] = new Post();
}
@action setCommentCountForPost(id, c) {
this._posts[id].setCommentCount(c);
}
getPosts() {
return this._posts;
}
}
let p = new PostList();
p.createPost(1);
autorun(function test () {
console.log(p.getPosts());
});
p.setCommentCountForPost(1, 22);