Leverage promises to alter reactive data, strategically placing them to minimize the frequency of triggers being activated

Initial Method

    const list = reactive([1, 2, 3, 4, 5]); 
    const clickHandler = () =>{
        list.push(...[11, 12, 13, 14, 15]);
        list.push(...[16, 17, 18, 19, 20]);
        Promise.resolve().then(() => {
            list.push(33)
        });
        
    };

Alternative Method

    const list = reactive([1, 2, 3, 4, 5]);
    const clickHandler = ()=>{
        Promise.resolve().then(() => {
            list.push(33)
        });
        list.push(...[11, 12, 13, 14, 15]);
        list.push(...[16, 17, 18, 19, 20]);
    };

The first approach results in two triggers of vue hooks onUpdated, while the second only triggers once. Can anyone explain why this difference occurs? Thank you.

Answer №1

Vue operates by updating data in a synchronous manner, collecting all changes to be processed in a microtask. If there is another microtask (such as Promise.resolve()) in your code, the order in which they are created can impact the sequence of events. In the first scenario, the vue-microtask is established before the Promise.resolve(), causing the Promise.resolve() to execute after the Vue update function, triggering another Vue update afterwards.

In the second scenario, the vue-microtask is set up after the Promise.resolve(), ensuring that the Promise has already been resolved by the time the vue-microtask runs. This allows any modifications to the list to be seamlessly integrated into the vue-microtask processing.

Answer №2

Vue's efficiency is due to its optimization mechanism that utilizes nextTick to batch updates.

In the initial method, multiple values are added to a reactive array, triggering the onUpdate hook once. Then, a separate cycle resolves the Promise, causing another trigger of onUpdate.

However, in the second method, the Promise resolves before any value additions to the array take place. This results in only one trigger of the onUpdate hook as Vue's reactivity detects and processes all operations within a single tick.

For more information: Learn why Vue updates only once when two close data mutations occur.

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

Encountering this issue when setting up the forgot password functionality or trying to submit a POST request using Postman

Below is the code snippet related to resetting a password: exports.forgotPassword = async function(req, res, next) { //Check if user exists const user = await User.findOne({ email: req.body.email }) if (!user) { return next(new App ...

Sustaining the Status of a Changeable Form Element

To fulfill the requirement of constructing a Form Builder component that generates forms based on JSON data from the backend, I have identified 7 types of input fields that may be encountered: email password select file date input of type text input of ty ...

Achieving success by correctly reaching the window's edge during an event (onscroll)

This happens to be my 1st inquiry. Specifically, I have a navigation menu with a transparent background and I am attempting to alter the background once it reaches the top edge of the window. window.addEventListener("scroll", navSticky); function navSt ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Discover the power of Vue.js 3 by seamlessly integrating anonymous functions within event handlers

Is it possible to invoke an anonymous function within an event handler in Vue.js 3? I came across several options on various websites: <button @click="return function() { console.log('test')}()">Click me</button> <butto ...

Retrieve information from a child component in Vue and link it to an object in the parent component

<user-data @change="setUserInfo"></user-data"> this particular component serves as the child element where data is passed using emits. Below is the snippet of code from the parent component. setUserInfo(data) { this.obj.paym ...

Tips for obtaining user input to place markers on a video timeline with JavaScript

I am new to Java script and I am trying to create a video player where users can click on the progress bar to place markers. Can you please review my code below and let me know if there are any errors? index.html <!doctype html> <html> <he ...

AngularJS directive does not trigger when switching tabs or scrolling pages

I came across a solution to display a placeholder image before the real image fully loads while browsing online here. I implemented the code provided in the accepted answer on my page, where I have two tabs using `ion-slide-box` for tab selection. Each tab ...

In Angular Typeahead, the model is used as an identifier and the Text represents the name in the array object

I'm currently utilizing the Angular UI Typeahead directive available at this link. Can someone provide guidance on how to assign a model as an id and display text as a name in it? I have attempted the method below but encountered issues. Any suggestio ...

Sending non-textual data within a JQuery ajax POST request

I have encountered an issue related to sending data from a JavaScript application to a Node.js server for database query purposes. Despite trying to find a solution from various sources, I have been unable to resolve it. Here is the code snippet used to s ...

Use Material UI Grid to create a horizontal line design instead of focusing on making the

Is there a way to turn off responsiveness for the material UI grid similar to how it can be done with a basic HTML table? While an HTML table scales down and adds a horizontal scroll bar, the material UI grid remains responsive as shown in the example belo ...

TypeScript error: Cannot find property 'propertyName' in the 'Function' type

I encountered an issue with the TypeScript compiler when running the following code snippet. Interestingly, the generated JavaScript on https://www.typescriptlang.org/play/ produces the desired output without any errors. The specific error message I recei ...

The scrolling function halts as soon as the element that was middle-clicked is deleted from the

I am knee-deep in developing my own React virtualization feature and encountering a minor annoyance. When I middle click on an item in the list and start scrolling, the scrolling stops once that item is removed from the DOM. My initial thought was that the ...

Do not use unnecessary variables for storing references in ES6

Despite using react es6, I am still unsure how to refrain from needing to use the variable that for this scenario: const that = this; UploadApi.exec(file).then(data => { that.setState({ loading : false}); }); ...

Choosing an option from a dropdown menu by extracting information from JSON content

My goal is to develop a basic jQuery plugin that interacts with a geolocation system to provide data on the location of the user's IP address and then automatically select the corresponding country in an HTML form. Within my HTML code, I have a selec ...

How can Typescript help enhance the readability of optional React prop types?

When working with React, it is common practice to use null to indicate that a prop is optional: function Foo({ count = null }) {} The TypeScript type for this scenario would be: function Foo({ count = null }: { count: number | null }): ReactElement {} Wh ...

software tool for managing state transitions

Can anyone recommend a superior javascript library for workflows? Right now, I'm utilizing Joint JS, but I require something with a more visually appealing interface (users tend to prefer that). ...

Tips for creating a clickable popover within a window that remains open but can be closed with an outside click

Is there a way to ensure that my popover window remains clickable inside its own area without closing, but automatically closes when clicked outside of the window? This is the code I am currently using, which is triggered by a button click: if (response. ...

Alter the font color upon clicking the menu using jQuery

When I click on the menu and sub-menu items, I want to change their colors along with their parent. You can see an example of how I want it to work here. However, currently, when I click on a sub-menu item, the color of the parent menu item gets removed. ...

A guide on invoking a JavaScript function after receiving a response from an AJAX request

I am facing an issue with a $.POST call that returns the name of a function to be executed, however, the function is not being triggered and I'm unsure why. Below is an example: JavaScript file snippet: $(function(){ $.post('test.php&apos ...