Incorporate fresh data into the updated vue3-chart

I am experiencing an issue with my Chart.js Chart in a Vue component that uses vue3-chart-v2. Initially, everything works fine until I attempt to update the data.

Currently, I am utilizing a watcher to monitor changes in the data. While the watcher functions correctly, updating the chart does not seem to work as expected.

My approach was to destroy the chart when the data changes and then re-render it with the updated data.

I have come across some related questions on stackoverflow regarding the use of mixins reactiveData/reactiveProp, but unfortunately, I am encountering an error when trying to access them through vue3-chart-v2.

If anyone could provide assistance, I would greatly appreciate it. This is my first question here on stackoverflow.

Here is the code snippet:

<script>
import { defineComponent } from 'vue';
import { Doughnut } from 'vue3-chart-v2';

export default defineComponent({
name: 'PieChart',
extends: Doughnut,
props: {
    carbonData: Object
},
data() {
return {
    chartData: {
        labels: ['Slabs', 'Columns', 'Foundation', 'Core'],
        datasets: [
            {
                data: [ this.carbonData.slabs, this.carbonData.columns, this.carbonData.foundation, this.carbonData.core ],
                backgroundColor: ['#8FBC8F', '#87CEFA', '#CD853F', '#e64e3e'],
                borderWidth: 1,
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        legend: {
            position: 'right',
        }
    }
}
},
mounted () {
    this.renderPieChart();
},
methods: {
    renderPieChart() {
        this.renderChart(this.chartData, this.options);
    }
},
watch: {
    carbonData : {
        deep: true, 
        handler() {
            this.state.chartObj.destroy();
            this.renderChart(this.chartData, this.chartOptions);
        },
   }
},

})
</script>

Answer №1

We have found success with a straightforward approach:

  1. Include a v-if statement in your chart, like v-if="renderChart"
  2. Set it to false initially, but switch to true when the data loads
  3. Each time you anticipate the data changing, toggle it back to false and then back to true once the update is complete.

This method has been effective for us over an extended period of time.

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

Accessing a Java class from another Java class within a Javafx application is a simple yet

When trying to call a class from another class in my JavaFX application, I encounter an issue. Specifically, I have created a pie-chart graph in Java that runs successfully when called individually. However, when I attempt to access this code from another ...

What is causing Node to mistake my MongoDB model for a module?

I've set up a basic MERN project with a UserModel included. import mongoose from "mongoose" const UserSchema = new mongoose.Schema({ name: String, email: String, password: String }) const UserModel = mongoose.model('Users', ...

Enable the event listener for the newly created element

I am attempting to attach an event listener to this HTML element that is being created with an API call handleProducts() function handleProducts() { var display = document.getElementById("display") var url = "http://127.0.0.1:800 ...

Is it possible to create a React Component without using a Function or Class

At times, I've come across and written React code that looks like this: const text = ( <p> Some text </p> ); While this method does work, are there any potential issues with it? I understand that I can't use props in this s ...

Text woven seamlessly with a series of different scenes

After contemplating the use of three.js for incorporating 3D visualization into my Sphinx extension for model visualization, I realized that the current tool I am using is outdated and not being maintained. The three.js library offers a variety of example ...

What are some ways I can receive a response promptly from a service in AngularJS?

After calling the service method from the controller, there is a delay in receiving the data that I need to populate a dropdown. My expectation is that when I call this method from the controller, it should return a response immediately, and then other log ...

Exploring the process of retrieving cookies on both the client and server side with Next.js 13

One of the functionalities in my code is a custom function called myFetch, which serves as a wrapper for fetch to include a token in the header. import clientCookies from "js-cookie"; import {cookies} from "next/headers"; const myFetch ...

Having trouble finding the sum of values in an array using the Reduce method?

I have always used a 'for' loop to calculate sums in tables, but recently I learned about a better way - using the 'reduce' method. Following documentation and examples with simple arrays was easy enough, but now I am working with an ar ...

performing an asynchronous mapping operation to update the elements of the array

I am working with an array that needs to undergo async.map processing. The parallel execution on each array object seems to be functioning correctly, with results logged as "Result for ...". However, the issue arises when the return callback from the itera ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...

Stop allowing the entry of zero after a minus sign

One of the features on our platform allows users to input a number that will be automatically converted to have a negative sign. However, we want to ensure that users are unable to manually add a negative sign themselves. We need to find a solution to pre ...

Having trouble retrieving JSON data from a local file using AJAX and jQuery

I am currently facing an issue with passing the content of json.txt in my PHP project folder to JavaScript. It was working fine yesterday, but today it seems that the browser is preventing it somehow... EDIT : Just to clarify, everything is on localhost, ...

perform validation middleware following completion of validation checks

Looking to establish an Express REST API, I aim to validate both the request parameters and body before invoking the controller logic. The validation middleware that I have put together is as follows: const { validationResult } = require('express-va ...

Resetting clears the date default value

When the page is loaded, the date input field is automatically set to the current date. However, if the form is reset, instead of restoring the default date, the date field is cleared, as shown in the images below: Page load Form reset // app.component. ...

Attempting to isolate SQL outcome in order to adjust price based on a percentage

I am currently working on a SQL search and results page that displays 3 columns of data: category, number, and price. However, the results are returned all together in one big lump. My goal is to have a dropdown list with percentages, where clicking on one ...

Navigating through directories (including nested ones) containing images in React Native; what's the best way to approach this

I am currently attempting to organize groups of images. Within the directory ./assets, there are several folders structured as follows: ./assets ├── 1x3 │ ├── 1.jpg │ ├── 2.jpg │ └── 3.jpg └── 3x3 ├── 1. ...

Modifying selections within a select box generated dynamically using JQuery

Looking for help on how to delegate to a static DOM element in my current situation. I need to create a dynamic select box .userDrop when .addNew is clicked, and then have the user select an option from #secDrop, triggering a change event that calls the da ...

Tips on passing an integer to an HTML page with Express.js routing

I've got this Express code that currently redirects to the views/index.html page. What I need now is to send some integers to index.html when a specific function executes in this code. Any suggestions on the most efficient way to accomplish this? cons ...

Another drop-down is hiding the bootstrap-select drop-down from view

What could be causing some parts of the first drop-down menu to be hidden by another drop-down menu below in the code snippet provided? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv= ...

Steps for inserting a button within a table

Currently, I have implemented a function that dynamically adds the appropriate number of cells to the bottom of my table when a button is clicked. This is the JavaScript code for adding a row: <a href="javascript:myFunction();" title="addRow" class= ...