The power of MobX lies in its ability to provide a deep

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);

Answer №1

MobX monitors property access rather than values

In the provided example, the autorun function only monitors _posts, not its properties. Therefore, if you change the value of _posts, the monitoring function will not be triggered.

console.log(toJS(p.getPosts())) functions properly because the toJS function is used to convert the observable value to a normal value by accessing the properties of _posts.

If you want p.getPosts() to work as expected, you need to iteratively access the properties of _posts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating custom elements for the header bar in Ionic can easily be accomplished by adding your own unique design elements to the header bar or

I'm a beginner with Ionic and I'm looking to customize the items on the header bar. It appears that the header bar is created by the framework within the ion-nav-bar element. <ion-nav-bar class="bar-positive"> <ion-nav-back-button> ...

How can I hover over multiple cells in a table?

Is there a way to change the color of multiple adjacent cells when hovering over one cell, and can this be done dynamically (so the number of adjacent cells that change color can vary)? Here is the code snippet: I'm using React to create a table wit ...

What is the best way to supply JSON data to the "The Wall" MooTools plugin while feeding?

I came across this amazing plugin called "The Wall" but unfortunately, neither the documentation nor the examples demonstrate how to utilize JSON objects with it. Imagine we have a JSON array like: [ { href : "/my/photo/image1.jpg", title : "Me an ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

Incorporate a Flask variable into a webpage seamlessly without refreshing the page

I am facing a challenge in importing the variable test_data from Flask to my webpage without having to reload it. I have tried clicking a button, but haven't been successful so far. Any suggestions? Flask: @blueprint.route('/data_analysis' ...

Learn how to utilize Vue 3 to access properties that have been passed down from a parent component, even if they

Hey there, hope everything is going well. I'm familiar with react.js, but when I gave vue a try, things felt a bit different. In react, it's easy to access props passed from the parent in the child component without much hassle. However, in vue, ...

Leverage JavaScript to retrieve the formatting of an element from an external CSS stylesheet

Check out this HTML snippet: <html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> ...

Utilizing Smart Table for Data Binding with JSON Dataset

I need help binding a JSON file to a smart table. How can I use the loop function for iteration? The design of the smart table is displaying, but the data from the JSON file is not binding. Here is the JSON file: [ { "year": 2013, "id ...

Unpredictable Behavior of CSS Transition with JS createElement() Function

I'm using JavaScript to create a div element and I'm adding the CSS property transition: .5s linear top; When the user clicks on the element (onmousedown event), it is supposed to smoothly move to the top of the screen and then be deleted using ...

Employing the `instanceof` operator on instances generated by constructors from complex npm dependencies

Context: In one of my npm modules, I've implemented error handling code with a custom error type called CustomError: function CustomError () { /* ... */ } CustomError.prototype = Object.create(Error.prototype); CustomError.prototype.constructor = Cu ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Navbar in bootstrap appears to be flashing when it is in its expanded

Example Link On smaller screens, the bootstrap navbar menu does not collapse by default when clicking on a menu item. To fix this issue, I added attributes data-toggle="collapse" and data-target="#navbar-collapse" to each menu item so that the menu will ...

Warning: npm is resolving peer dependency conflicts during the installation process

Upon running npm install for my React application, I encountered the following warnings in the logs. Despite that, the npm installation completed successfully and the dependencies were added under node_modules. My app even starts up without any issues. I ...

Issues with React - Material UI Menu functionality

I'm encountering an issue with the menu/menu item component from material ui when trying to render it based on a condition. Here is my code snippet... const AddSelectItemButton = () => { return ( <> <Fab ar ...

What could be causing my code to become unresponsive when using a for loop compared to a loop with a specific

After spending a solid 4 hours on it, I finally managed to figure it out. There were no errors popping up, so I resorted to using the debug feature which unfortunately didn't provide much insight. Without any error messages to guide me, I wasn't ...

Guide to Utilizing the Import Function in a Vue 3 Template

Working on a Vue 3 project, my setup includes a stuff.ts file with helpful functions that I need to utilize in my template. <script lang="ts"> import { defineComponent, onMounted } from 'vue' import { doSomething } from ' ...

JavaScript Regular Expression for separating a collection of email addresses into individual parts

I am very close to getting this to work, but not quite there yet. In my JavaScript code, I have a string with a list of email addresses, each formatted differently: var emailList = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Display the changing value at the beginning of the drop-down menu

I'm currently working on an AngularJS forEach loop where I need to display a dropdown list with dynamic values. The goal is to have the value stored in $scope.showCurrentProgram as the first selected element in the dropdown list when the page loads, a ...

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

Retrieving the Vue component object while inside the FullCalendar object initialized within the component

When using Full Calendar with VueJS, I ran into a problem where I needed to open a custom modal when clicking on a time slot in the calendar. The issue was that I couldn't call a function outside of the Full Calendar object to handle this. This is bec ...