Home > front end >  How to calculate array while rendering [Vue.js] - Infinite loop error
How to calculate array while rendering [Vue.js] - Infinite loop error

Time:12-01

This is my code in parent component:

                   <div
                            v-for="measurement
                             in measurements"
                            :key="measurement.id"
                   >
                            <graph-component
                                :value="valueOfMeasurement(measurement)"
                            ></graph-component>
                  </div>

I send props value to child component graph-component. :value should send array to graph-component but I get error You may have an infinite update loop in a component render function..

MethodvalueOfMeasurement(measurement) is:

methods:{

     valueOfMeasurement(measurement) {
                this.arrayOfValues.length=0;
                this.counter=0;
    
                for( this.counter;this.counter<this.message.feeds.length;this.counter  )
                {
                     this.arrayOfValues.push(this.message.feeds[this.counter]["field"   measurement.fieldId]);
                }
                return this.arrayOfValues;
                
            }
}

Im beginner to Vue.js and I assume that I get this error because I push new elements to array, but I can't find other way to do this.

CodePudding user response:

You're getting a possible infinite loop because you are mutating state during the render. Specifically, you are calling the valueOfMeasurement method during the render (i.e. within the template) which is modifying the component state (this.arrayOfValues and this.counter). This will trigger Vue to re-render again, which then mutates the state again, and so on infinitely.

Why are arrayOfValues and counter local state? You're just clearing them each time the method is called anyway, so it seems they should just be local variables within the method. But... that depends on if <graph-component> mutates these arrays; if so you should pre-compute all of this data ahead of time outside of the template, perhaps when measurements is first set or in created hook, etc.

  • Related