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

The issue arises when PhantomJS and Selenium fail to execute iframe JavaScripts while attempting to log in to Instagram

Currently utilizing Python alongside Selenium and PhantomJS, I encountered an issue while attempting to login to Instagram. It seems that PhantomJS is unable to process iframes' JavaScripts properly; interestingly, when trying the same action with Fir ...

The G/L account specified in the SAP B1 Service Layer is invalid and cannot be used

I attempted to generate a fresh Incoming payment utilizing the service layer, but encountered this issue G/L account is not valid [PaymentAccounts.AccountCode][line: 1] Here is my JSON: { "DocType": "rAccount", "DueDate& ...

Mastering the Art of Utilizing .less Files in Nuxt.js

I have recently created a .less file in the Nuxt folder located at assets/css/myfile.less, where I included some CSS styles. .edit-btn-color { background-color: #b1c646; color: white; } .edit-btn-color:hover { background-color: darken(#b1c646, 10%); ...

Leveraging the result of one ajax function within a different ajax function

My current project involves the following steps: 1. User creates a template with various elements. 2. When the user clicks a button: *The first ajax function establishes a new entry in the custom template database. *The second ajax function retrieves the ...

The website experiences a sudden crash shortly after launching, displaying the error message "EADDRINUSE" for port 80

PROBLEM I have a react-based website running on a node-express server. My backend server is working fine on port 3000, but the website on port 80 keeps crashing. When I use pm2 to start my website (https://www.edvicer.com) with the command pm2 start serv ...

What is the proper way to utilize the script type "text/x-template" in a multilanguage context?

I'm currently working with ASP NET and VueJS. In my ASP NET, I have a view component that looks like this: <script type="text/x-template" id="form-template"> @if (string.IsNullOrEmpty(Model.LastName)) { <in ...

Decoding the Blueprint of Easel in JavaScript

Recently, I came across a fantastic API that promises to simplify working with CANVAS by allowing easy selection and modification of individual elements within the canvas. This API is known as EaselJS, and you can find the documentation here. While I foun ...

The pagination feature in DataTable does not retain the edited page after making changes

I have been encountering an issue while using DataTable serverside processing. My datatable includes an edit column, and when the edit link is clicked, a jQuery dialog box appears. After submitting the dialog box, an ajax.reload call is made. However, the ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

Guide on sending emails with AngularJS and the Ionic framework

I have been attempting to send an email by using various links, but without success. I am looking for guidance on how to successfully send an email. Below is the code I have been using for sending emails. Any suggestions for changes would be greatly apprec ...

Utilize jQuery method in HTML to perform parsing operation

Is it possible to invoke my jQuery function from within my HTML code? Here is the code snippet: HTML section: <td style="text-align:left;" align="left" > <div id="bulletin-timestamp" > doTimeStamp(${bulletinTimeStamp[status.index ...

Looking for assistance with accessing elements using the "document.getElementById" method in Javascript

Below is the code snippet I am working with: <html> <head> <script> function adjustSelection(option) { var selectList = document.getElementById("catProdAttributeItem"); if (option == 0) { ...

Creating a specific quantity of divs with JavaScript

For the past few hours, I've been working hard to solve this problem that has really left me stumped. As far as I can tell, everything is correct. The create function is supposed to generate a certain number of divs specified by the user in an input b ...

jQuery tabs become non-functional following submission of form

I have a form contained within a jQuery tab div that is loaded using AJAX: <div id="tabs-2"> <form id="frmLogin" name="frmLogin" class="cmxform" method="post" action="actions/login.php"> <p> <label>Username& ...

Retrieve targeted information from MySql using jQuery AJAX Success

I've got this AJAX code set up to retrieve data from MySQL and display it in the Success block. $.ajax({ type:"POST", url:"index.php", success: function(data){ alert(data); } }); This is my Query $sql ...

Exploring the Realm of Angular Controllers and Services: Embracing Triumphs and

Currently in the process of creating a service layer for an existing web app using Angular. I am transitioning $http requests and data manipulation to custom Angular services. While I have a good understanding of Dependency Injection in services, I am enco ...

Can these two arrays be merged together in JavaScript?

Here is the structure of the first array: [ 0:{program: id_1}, 1: {program: id_2} ] Now, let's take a look at the second array: [ 0: [ 0: {lesson: name_1}, 1: {lesson: name_2} ], 1: [ 0: {lesson: name_3} ] ] I am attempti ...

open a fresh modal by closing the existing modal using just one button

I am trying to implement a unique functionality in my bootstrap based project. I have one modal that I want to link to another modal, however, I am facing some challenges in achieving this. Currently, I am attempting to use the modal.close() and .modal(&ap ...

The function is malfunctioning following the alert

I am experiencing an issue with my renumbering list function. I have a delete button on the list that triggers a confirmation alert, but after the alert is shown, the renumbering function stops working. Here is my script: <script type="text/javascript ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...