Unending cycle occurs when utilizing a computed property alongside Vue Chart js

My goal is to refresh my chart with new data from an API call every 5 seconds. However, the chart is updating excessively, rendering each point hundreds of times. After checking the logs, I discovered that there seems to be an infinite loop causing this issue, and I'm unsure how to fix it. Below is the current code snippet:

Please note: The 'graphData' prop is an Array passed from the parent component containing the data retrieved from the API.

ChildComponent.vue

<template>
<div class="graphCard">
    <Linechart :chartData="dataCollection" :options="options" />
</div>
</template>


<script>
import Linechart from '@/utils/Linechart.js'

export default {
components: {
    Linechart
},
props: ['graphData'],
data() {
    return {
        collection: []
    }
},  
computed: {       
    dataCollection() { 
        this.collection.push(this.graphData[0])
        return { 
            datasets: [
                    {
                    label: 'chart',
                    backgroundColor: 'indigo',
                    borderColor: 'indigo',
                    fill:false,
                    showLine: true,
                    data: this.collection
                    }]
        }    
},
options() {
        return {
            id: 'Cumulative',
            legend: {
                display: false
            },
            scales: {
                xAxes: [{
                    type: 'time',
                    distribution: 'series',
                    time: {
                        displayFormats: {
                            millisecond: 'mm:ss:SS',
                            quarter: 'MMM YYYY'
                        } 
                    }
                }],
                yAxes: [{
                    ticks: {
                        //beginAtZero: true
                    }
                }]
            }
        }
    }

LineChart.js

import { Scatter, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
    extends: Scatter,
    mixins: [reactiveProp],
    props: ['chartData', 'options'],
    mounted () {
        this.renderChart(this.chartData, this.options)
    }
}

I also attempted an alternative approach by setting up 'dataCollection' and 'options' as 'data' instead of 'computed,' along with a watcher on the 'graphData' prop. However, the chart failed to update and threw an error "Uncaught TypeError: Cannot read property 'skip' of undefined."

Answer №1

Typically, a computed method is preferred over a watcher. However, troubleshooting an infinite loop issue requires more context to resolve. In the meantime, consider using the combination of data and watch as an alternative solution.

Check out the code snippet below:

<template>
<div class="graphCard">
    <Linechart :chartData="dataCollection" :options="options" v-if="dataCollection.datasets[0].data.length"/>
</div>
</template>

<script>
import Linechart from '@/utils/Linechart.js'

export default {
    components: {
        Linechart
    },
    props: ['graphData'],
    data() {
        return {
            dataCollection: {
                datasets: [{
                    label: 'chart',
                    backgroundColor: 'indigo',
                    borderColor: 'indigo',
                    fill:false,
                    showLine: true,
                    data: []
                    }]
            },
            options: {
                id: 'Cumulative',
                legend: {
                    display: false
                },
                scales: {
                    xAxes: [{
                        type: 'time',
                        distribution: 'series',
                        time: {
                            displayFormats: {
                                millisecond: 'mm:ss:SS',
                                quarter: 'MMM YYYY'
                            }
                        }
                    }],
                    yAxes: [{
                        ticks: {
                            //beginAtZero: true
                        }
                    }]
                }
            }
        }
    },
    watch: {
      graphData (newData) {
        this.dataCollection.datasets[0].data.push(newData[0])
      }
    }
}

Answer №2

@BTL helped steer me in the right direction, but there were still some issues that needed to be addressed for the graph to update correctly. It appears that the chartData was not updating properly when new data was directly pushed onto the dataset. Here is the workaround that proved successful for me:

watch: {
    graphData (newData) {
        currentDataList.push(newData[0])
        this.dataCollection = { 
            datasets: [{
                label: 'label',
                backgroundColor:'red',
                borderColor: 'red',
                fill:false,
                showLine: true,
                lineTension: 0,
                data: currentDataList
            }]
        }
    }
}

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

Unable to remove data once it exceeds 10 entries while using AJAX, jQuery, and JavaScript/PHP

I am having an issue where I can insert data into the first 10 rows and delete any of them successfully. However, when I try to insert data starting from the 11th row, I am unable to delete any rows past the 10th. UPDATE: The deletion function does not wo ...

A guide on how to efficiently retrieve all images stored in a specific directory

I attempted to showcase all the images from a single directory using jQuery, but unfortunately it is not functioning as expected. My folder setup includes an 'images' folder and a 'js' folder. I followed this question on Stack Overflow ...

How can you determine if a user has selected "Leave" from a JavaScript onbeforeunload dialog box?

I am currently working on an AngularJS application. Within this app, I have implemented code that prompts the user to confirm if they truly want to exit the application: window.addEventListener('beforeunload', function (e) { e.preventDefault ...

Exploring Vue.js3: Simplifying Nested Array Filtering

Currently, I am in the process of sifting through an Array that contains nested arrays. To handle this task, I utilized computed and crafted a function called filteredEgg(). However, I seem to be overlooking something, as I'm only returning the main ...

Challenges with Vuex and updating arrays using axios

I am currently facing a challenge with VueJS Vuex and Axios: The issue arises when I retrieve an array with Axios and loop through it to populate its children this way: "Rubriques" has many self-relations, so one rubrique can have multiple child rubriques ...

Having issues with $emitting not working for parent-child components in Vue. Any ideas on what I might be doing incorrectly?

I have a login component that I need to call in the main vue component of App.vue. Within the login vue, when I click on any button, it should activate another vue component using Vue.js router to replace the login page. I have searched for solutions but h ...

What are alternative methods for creating a two-column form layout that do not involve the use of

When generating the html form, I am looping through the form variables as shown below: {% for field in form %} {{ LABEL }}{{ INPUT FIELD }} The labels and fields are going through a loop. A simple one-column layout can be generated using: {% for field ...

The mouse coordinates do not align with the drawing of a rectangle on the canvas

I am having some issues with drawing a rectangle on mouse drag over the canvas that is overlayed on an HTML5 video JS player. The rectangle is being drawn, but it does not align correctly with the mouse coordinates. I suspect that the canvas, which is ove ...

Changing the content of the initial post in a loop on WordPress

<?php $freeadvice=new WP_Query('category_name=freeadvice&showposts=10'); while($freeadvice->have_posts() ): $freeadvice->the_post(); ?> <li class="event"> <input type="radio" name="tl-group" /> ...

Ensuring the safety of PHP JSON output results on a web server

I am currently developing an app using phonegap that submits and retrieves data from a MySQL database hosted on a server (website). I have successfully implemented the data submission and retrieval features in the app. The data is fetched through AJAX fro ...

Share your ES module (.mjs) on NPMJS with support for Node versions older than 8.5.0 (Dual Package)

In the past, publishing a module written in ES6 to NPMJS was a simple process: transpile the code using Babel and publish the resulting `lib` directory to NPMJS while keeping the original `src` files on GitHub. However, with Node v8.5.0's experimenta ...

What is the best way to conceal a global component like a navbar on specific routes?

Most of the pages on my vuejs SPA feature a top navbar component, but there are certain views like the login page where I do not want it to be displayed. My current solution involves importing the navbar and adding it to each view separately when needed. ...

In Discord.js, the client.login() promise seems to be stuck and never resolves, causing the client.on("ready") event to never be

After creating a simple Discord bot using discord.js, I programmed it to respond with the message "Good morning to you too" whenever someone sends a message containing "good morning". Surprisingly, this feature worked seamlessly until recently when the bot ...

Why does the Vue i18n $t('hello') not function properly within a data property until the page is refreshed, yet it works fine when used in a normal template?

**Below are the components I require assistance with: The home component contains an array that needs to have its title and content translated, then binded as props to the info component. Since $t does not work with data method, how can I accomplish this u ...

Exploring the Contrast between router-link and RouterLink in VueIn this article

During my exploration of Vue Router, I noticed that I could use both <router-link> and RouterLink to accomplish the same task of navigating between different routes. Similarly, there's the existence of <router-view> alongside the RouterVi ...

Inconsistent rendering issue identified in AngularJS when updating arrays with ui-router

I'm leveraging ui-router to navigate to specific subpages in my application: var myApp = angular.module("myApp",['ui.router']); myApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('usergroups&apos ...

What is the best way to incorporate an immediately invoked function expression (IIFE) within the return statement of a React

I currently have a modal that pops up when the user clicks a button on my page and it's functioning perfectly: render() { return ( <div> <section> <button onClick={() => this.refs.simpleDialog.show()}> ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

"Embracing Dynamism: Enhancing Vue3 with Dynamic Routing for

Seeking guidance on implementing a dynamic component with Dynamic Routing in Vue3. The goal is to render a component based on the parameter (path named id) from router.ts. In the router.ts file, there is a dynamic parameter called id that needs to be used ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...