What is the best way to ensure that Vue updates data dynamically in real-time?

The product component displayed below allows users to view the macro nutrient information of a product and also modify the serving size, which automatically updates the macro nutrient amounts.

However, I am encountering an issue where the values are not being updated correctly, even when using "vue set".

I have implemented a watcher to trigger the calcNewNutriValues function.

<template>
    <div class="product">
        <div class="topbar">
            <div class="left">
                <p class="left__name">{{ product.name }}</p>
                <p class="left__energy">{{ product.energy }}</p>
            </div>
            <div class="right">
                <button class="cancel" @click="removeItem">
                    <inline-svg
                        :src="require('../assets/svg/addition-icon.svg')"
                    ></inline-svg>
                </button>
            </div>
        </div>
        <div class="details">
            <div class="macros">
                <p class="details__heading">Macros</p>
                <div class="macros__container container">
                    <div class="wrapper" v-for="(macro, name, index) in product.macros" :key="index">
                        <p>{{ name }}</p>
                        <p>{{ product.macros[name] }}</p>
                    </div>
                </div>
            </div>
            <div class="serving">
                <p class="details__heading">Serving Size (g)</p>
                <input type="number" placeholder="40" v-model.number="productServSize">
            </div>
        </div>
    </div>
</template>
export default {
    data () {
        return {
            productServSize: 0,
            ogServSize: 0,
            macros: {
                protein: '',
                carbs: '',
                fats: '',
                fibre: ''
            },
            micros: {},
            energy: ''
        }
    },

    props: [
        'product',
    ],

    methods: {
        serving () {
            const num = this.product.servingSize.split(' ')[0]
            this.productServSize = parseFloat(num)
            this.ogServSize = parseFloat(num)
        },

        removeItem () {
            this.$emit('removeProduct', this.product)
        },

        calcNewNutriValues () {
            Object.keys(this.product.macros).forEach(key => {
                let num = parseFloat(this.product.macros[key].split(' ')[0])
                let perGram = parseFloat(num / this.ogServSize)
                let newTotal = `${(perGram * this.productServSize).toFixed(1)} g`
                this.$set(this.macros, key, newTotal)
            })
        }
    },

    mounted () {
        this.serving()
        Object.assign(this.macros, this.product.macros)
        this.energy = this.product.energy
    },

    watch: {
        productServSize: {
            handler () {
                this.calcNewNutriValues()
                this.$emit('updatedNutriValues', this.product)
            }
        }
    }
}

Answer №1

If you believe that the macros data is not updating, it may actually be due to how your template is set up. Your current code displays product.macros instead of just macros:

<div class="container" v-for="(macro, name, index) in product.macros" :key="index"> 
  <p>{{ name }}</p>
  <!-- <p>{{ product.macros[name] }}</p>  AVOID THIS -->
  <p>{{ macros[name] }}</p>
</div>

Check out the demo here

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

Utilizing a class function within the static method `getDerivatedPropsFromState`

I've been updating the deprecated life-cycle method componentWillRecieveProps() to its new replacement static getDerivatedPropsFromState(). The issue I'm encountering with this update is that componentWillRecieveProps() uses a class function int ...

Building an LED display with three.js

I have a project where I am creating a board with multiple RGB LEDs mounted on it, as shown in the image. https://i.sstatic.net/WtOm4.png To create the LEDs, I used the following code: this.light = new THREE.PointLight(color, intensity, distance, decay) ...

Load the file's contents into an array within a Vue component

https://i.sstatic.net/gxcYi.png My media.txt file contains the following URLs: "https://www.dropbox.com/s/******/687.jpg?dl=0", "https://www.dropbox.com/s/******/0688.jpg?dl=0 Incorporating a Vue carousel component: <template> <section> ...

What techniques are most effective for creating unit tests in a Node.js environment?

One of the challenges I am facing is writing a unit test for a module where I load a mustache template file. To tackle this, I am exploring the use of mocha, chai, and rewire. Below is an excerpt from my module.js: var winston = require('winston&apo ...

Achieving a child div to occupy the entire available space when the parent is specified as `mx-auto` can be accomplished using Vue and Tailwind CSS

Sorry if this seems like a basic question, I'm still getting the hang of Vue and tailwind. In my parent template, it looks like this: <template> <div class="mx-auto mt-4 max-w-3xl"> <slot></slot> </div> ...

Finding the parent div in the handleChange function using React

I am facing a challenge with multiple dynamic divs, as their number depends on the filter selected by the visitor. This makes it impossible to use getElementById in this scenario. My goal is to modify the parent div's CSS when an input is checked. B ...

Protect your Vercel Next.js serverless function with secure authentication mechanisms

I'm looking to restrict access to my GraphQL API to authenticated users only. I've been using Apollo GraphQL Studio to test my API, and I've successfully set the auth token in the header. However, I'm unsure of how to retrieve and use t ...

Obtaining an Array through a direct input on the command line

I am having trouble incorporating raw command line arguments in my Node.js application. When I try with simple variables, everything works as expected (node example.js variable) However, when I pass an array as an argument, it does not work properly (n ...

Transferring the values of JavaScript objects to HTML as strings

My goal is to generate HTML elements based on the values of specific JavaScript objects that are not global variables. However, when attempting to execute the code below, I encounter an error stating "params is not defined." What I actually aim to achieve ...

Error: Property 'blogCategory' is unreadable because it is undefined

Having trouble rendering blog posts from a json file in React const BlogPost = (props) => { const [post, setPost] = useState({ id: "", blogCategory:"", blogTitle:"", postedOn:"", ...

Could you tell me how to determine the height of a page when converting it to a PDF?

I am facing a challenge trying to render a dynamic content PDF using puppeteer and react. The layouting is handled in Material UI for react, so using page-break-before:always is not feasible as it conflicts with the flex grid layout. My goal is to determin ...

Is there something else I should consider while implementing onBlur?

I am currently working on implementing form validation for a React form that I have developed. The process involves using an onChange event to update the state with the value of each text field, followed by an onBlur validation function which checks the va ...

Dynamic backdrop featuring engaging content

I am currently working on a WordPress website that features a dynamic background. While I have successfully implemented movement to the background, the content on the site remains static and unaffected by scrolling. The background does not move alongside t ...

Developing in Node.js involves setting a specific timezone while creating a date

I feel like I'm overcomplicating things here. My server is running on nodejs, and the front-end is sending me an offset. What I need is to determine the UTC equivalent of yesterday (or today, or last week) based on this offset. Currently, my code l ...

How to effectively handle form CRUD operations in Angular 2/4 using parent and child components

In my setup, there is a parent component along with a child component. The parent mostly consists of a list of repeating children created using *ngFor directive. Each child component receives an object through Angular's @Input feature, and the child ...

How to update a value within a deeply nested array in MongoDB and then sort the data

In my document, I have a list of timestamps that are sorted by time: { _id: '1', timestamps: [ { id: '589b32cf-28b3-4a25-8fd1-5e4f86682199', time: '2022-04-13T19:00:00.122Z' }, { id: '781 ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

JavaScript Time Counter: Keeping Track of Time Dynamically

Currently, I am attempting to create a dynamic time counter/timer using JavaScript. Why dynamic? Well, my goal is to have the ability to display days/hours/minutes/seconds depending on the size of the timestamp provided. If the timestamp is less than a d ...

Getting the value of a variable within the scope of AngularJS can be achieved by utilizing

I have an ng-repeat directive in my code that displays slides. Here is a snippet of the data: slides = [{ src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_24.jpg", interval: 5000 }, { src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_login-regi ...

AngularJS and CSS: A Guide to Effortlessly Toggle Sliding List Elements

I am in the process of developing a drop-down menu that can be clicked. Using my custom AngularJS directive, I have successfully implemented functionality to load menu items dynamically. While I have made significant progress, I have encountered a small i ...