Async reaction in MobX is a powerful tool for handling

Hey there, I am currently utilizing MobX in a store and faced with the need for an asynchronous reaction to occur when a computed value changes:

class Store {
    @observable user;
    @observable something;

    @computed get firstParam () {
         return this.user && this.user.params[0];
    }

    async loadSomething () {
        reaction(
                () => this.firstParam,
                async (param) => {
                    const { data: something } = await axios.get(`url/${param}`);

                    runInAction('update state after fetching something', () => {
                        this.something = something;
                    });
                }
            );
     }

}

I'm intrigued about the potential differences between using when instead of reaction, aside from just the running condition. Any thoughts?

when(
    () => !!this.firstParam,
    async () => {
         // fetch using this.firstParam
    }
)

Answer №1

Keep in mind that when only triggers its effect once before stopping. This means that in your situation, the data will be fetched just one time.

Answer №2

        reaction(
            () => this.firstParam,
            async (param) => {
                const { data: something } = await axios.get(`url/${param}`);

                runInAction('update state after fetching something', () => {
                    this.something = something;
                });
            }
        );

This particular code snippet is designed to monitor changes in this.firstParam. When a new value is returned for this parameter, it triggers an asynchronous function:

            async (param) => {
            const { data: something } = await axios.get(`url/${param}`);

            runInAction('update state after fetching something', () => {
                this.something = something;
            });

Regarding the usage of when, the MobX documentation suggests that observable data can be treated as a promise. Upon completion of the asynchronous action, the data can be updated accordingly. Therefore, there seems to be no inherent drawback in using when in your scenario.

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

Does this Loop run synchronously?

Recently, I crafted this Loop to iterate through data retrieved from my CouchDB database. I am curious whether this Loop operates synchronously or if async/await is necessary for proper execution. database.view('test', 'getAllowedTracker&ap ...

Unusual AngularJS error encountered while performing calculations on object properties

After running a specific calculation in my code, I encountered an unexpected issue. if (typeof $scope.memoryTable[name][category]['total'] !== 'undefined') { $scope.memoryTable[name][category]['total'] = $scope.memoryTabl ...

Utilizing a CSV file as a Map with D3 and JavaScript

After thorough research through JavaScript and D3 documentation, I have not been able to find a solution to my problem... Is it feasible to import a CSV file with the following format: header, header string1, string string2, string ... stringN, string an ...

"Customizing the Material-ui TextField DOM Element: A Step-by-Step

After trying the code below, I was expecting to see a yellowish "Hi," but instead received [object Object]. Is there a way to correct this issue? Possibly utilizing InputProps would help, but I haven't been able to locate a comprehensive tutorial on ...

The custom radio button I created is not functioning as expected in JavaScript

The JavaScript I wrote for my custom radio button is not working properly. When I check the console, it shows an error message: Uncaught SyntaxError: Unexpected token } on line 14. Here is the code snippet that I used: $(document).ready(function() { ...

Leveraging the On Keyup Function in Real-Time

How can I modify this code to run after an ajax call using .live method? var element=document.getElementById('txt_url'); element.onkeyup=function(){ var input=element.value; if(input=='') return; if(input.indexOf('h ...

Encountering a jQuery error while trying to utilize the $window.load

I have a code snippet that is functioning well when wrapped within a document ready event: jQuery(document).ready(function($) { $('tr[data-name="background_colour"] input.wp-color-picker').each(function() { //this section works fin ...

The jQuery AJAX response consistently comes back empty

Hello, I'm currently working on creating an HTML form and I need to validate it before submitting the form action. However, when I use AJAX to respond, I keep receiving a blank message. Can anyone help me with this issue? $(function(){ $("#ajax-p ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

Updating database with Ajax when the button is clicked

Seeking guidance with a project as I am still grasping the concepts of javascript and jquery. The goal is to update a database entry upon clicking a button, where the content of the button is fetched from the database. Initial step involves querying the d ...

Run a script on a specific div element exclusively

Up until this point, we have been using Iframe to load HTML and script in order to display the form to the user. Now, we are looking to transition from Iframe to DIV, but we are encountering an issue with the script. With Iframe, the loaded script is onl ...

Comparing the efficiency of using arrays versus mapping to an object and accessing data in JavaScript

When considering the basics of computer science, it is understood that searching an unsorted list typically occurs in O(n) time, while direct access to an element in an array happens in O(1) time for HashMaps. So, which approach yields better performance: ...

Transmit data to a modal using JSX mapping technique

When working with a map that renders multiple items, how can I efficiently pass parameters like the item's name and ID to a modal component? render(){ return( <div> <Modal isOpen={this.state.OpenDel ...

Universal HTML form validation with a preference for jQuery

Is there a jQuery plugin available for form validation that follows the most common rules? Specifically, I need to validate based on the following criteria: All textboxes must not be empty If the 'Show License' checkbox is checked, then the &a ...

What is the best way to set a boolean value for a checkbox in a React project with Typescript?

Currently, I am working on a project involving a to-do list and I am facing an issue with assigning a boolean value to my checkbox. After array mapping my to-dos, the checkbox object displays 'on' when it is unchecked and a 'Synthetic Base E ...

Employ the setInterval function to run a task every 15 minutes for a total of

I have a task that requires me to use setInterval function 5 times every 15 minutes, totaling one hour of work. Each value retrieved needs to be displayed in an HTML table. Below is the table: enter image description here For example, if it is 7:58 p.m. ...

I am curious if there is a wysiwyg web editor extension specifically designed for VS2010 available?

In my experience, I have been working with C#, HTML coding using VS2010 and MVC. Utilizing VS2010 has proven to be an invaluable tool for me in this process. Currently, I find myself needing to create some straightforward static web pages. I am wondering ...

Webpack is notorious for creating multiple copies of images

Having an issue with Webpack where it's generating duplicate images, one of which is broken. I have an original image image, and after running Webpack, two duplicates are created. One works fine: image, but the other one is broken: image. I'm us ...

Exploring the power of regular expressions in Javascript when used between

Consider the scenario outlined in the text below I desire [this]. I also desire [this]. I do not desire \[this] I am interested in extracting the content enclosed within [], but not including \[]. How should I approach this? Currently, I have ...

Identification of input change on any input or select field within the current modal using JavaScript

My modal contains approximately 20 input and select fields that need to be filled out by the user. I want to implement a JavaScript function to quickly check if each field is empty when the user navigates away or makes changes. However, I don't want t ...