The data in the Vue 3 Chart.js is being updated from an API source, however, the chart is not

Vue 3 Chartjs Not Updating Data Dynamically from API

I am currently working on Vue 3 and I am new to it. I added a chart using the official Chart.js documentation, and initially, everything rendered correctly when I populated the chart with data from an API. However, when I tried to update the data field to another set of data, the chart was not rendering despite receiving the updated data.

Below is the JSON data retrieved from the API:

[{"ward":1,"maleCount":3,"femaleCount":1,"otherCount":1,"disableCount":0}, 
{"ward":2,"maleCount":0,"femaleCount":0,"otherCount":0,"disableCount":0}, 
{"ward":3,"maleCount":0,"femaleCount":0,"otherCount":0,"disableCount":0}, 
{"ward":4,"maleCount":0,"femaleCount":0,"otherCount":0,"disableCount":0},

This is how the API is called in my code:

 mounted() {
    this.getData();
  },

method:{
getData() {
      axios
        .get("api/v1/household/dashboard/getDetailByGharMuli")
        .then((res) => {
          // Handling the retrieved data
        })
        .catch((err) => {
          console.error(err);
        });
    },
barChart() {
      // Function to create the bar chart using Chart.js library
    },
}

I attempted to update the data according to Ward 1 from the JSON data mentioned above. However, even though the chart received the updated data, it failed to render. This is the function responsible for updating the data:

setDataBywardID(data) {
      axios
        .get("api/v1/household/dashboard/getGenderCountAccordingToWard/" + data)
        .then((res) => {
          // Processing the updated data
        })
        .catch((err) => {
          console.log(err);
        });
    },

Answer №1

Typically, when updating a chart, it's not necessary to call new Chart every time.

The best practice is to save the chart upon creation (by adding chart: null to data), so you can easily check if it already exists when invoking your barChart function.

For further information, refer to Updating Charts

Here is an example implementation:

barChart() {
    var Chart = require("chart.js");
    var options = {
        type: "bar",
        data: {
            labels: this.llabels,
            datasets: [
            {
                label: "Male Population",
                backgroundColor: "rgba(0, 143, 251, 0.8)",
                data: this.mdata,
            },
            {
                label: "Female Population",
                backgroundColor: "rgba(0, 227, 150, 0.8)",
                data: this.Fdata,
            },
            {
                label: "Other Population",
                backgroundColor: "rgb(255, 69, 96,0.8)",
                data: this.Odata,
            }]
        }
    };

    if(!chart)
        this.chart = new Chart(document.getElementById("bar-chart-grouped"), options);
    else
    {
        this.chart.options = options;
        this.chart.update();
    }
}

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

Ways to identify if the text entered in a text area is right-to-left justified

Within a textarea, users can input text in English (or any other left-to-right language) or in a right-to-left language. If the user types in a right-to-left language, they must press Right-shift + ctrl to align the text to the right. However, on modern O ...

The firebaseui.js code encountered an error because it was unable to read the property 'call' as it was undefined

Currently, I am facing an issue while trying to implement Firebase ui auth in my app by referring to Google's Github documentation. While the email sign-in functionality is working smoothly, I am encountering problems with the phone sign-in option. ...

Using CSS classes with IDs within a Vue application

Hello, this is my first time posting on SO. I am facing an issue with attaching a CSS class to an element with an ID. I have successfully implemented the functionality using classes by toggling states upon clicking an HTML element. However, when trying to ...

Generate a dynamic list using NG-Repeat with changing classes

Is there a way to print each item that matches the index of the first loop as an li element with different classes? For instance, having li elements with classes like cat1_li, cat2_li, cat3_li for each respective loop iteration. I'm struggling with ...

Assistance with utilizing Google Sheets scripts for retrieving formulas is needed

I've been working on a small search tool in Google Sheets as a personal project to improve my skills and knowledge of GS. Munkey has been guiding me over the past few weeks and helping me develop my understanding. Below are the links to my "Database" ...

Ways to activate onChange multiple times for a single item within material ui's autocomplete feature

I am utilizing the autocomplete component in the Material UI. Upon selecting an item, the onChange props are triggered and certain actions are performed. However, I am encountering an issue where I can select the same object multiple times without the on ...

Tips for deploying a Nuxt application using an alternative command line interface

Despite my best efforts scouring the internet for a solution, I have yet to find a method to resolve my issue. The problem lies with my nuxt.js SPA being blocked by my company firewall when accessed by other users at the designated host/port. While servin ...

PhpStorm IDE does not recognize Cypress custom commands, although they function properly in the test runner

Utilizing JavaScript files within our Cypress testing is a common practice. Within the commands.js file, I have developed a custom command: Cypress.Commands.add('selectDropdown', (dropdown) => { cy.get('#' + dropdown).click(); } ...

What is the best way to retain previous values without using an object array to store values in a React state?

My approach involves storing the previous values in an array of objects, where each object represents a key-value pair. For example: [{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]. However, I aim to transform ...

Failure of Angular to execute HTTP calls asynchronously

I am feeling a bit perplexed about how and when to use the .then and/or .success functions. Here is a function example: $scope.handleData = function(option){ if(option == 1){ link = firstLink/; }else{ link = secondLink/; } ...

Version 5.0.4 of Mui, when used with makeStyles and withStyles, is experiencing issues with applying styles to Mui

I've been diving into a react project using Mui v5.0.4 and encountered an unexpected issue with my custom styles. Initially, everything was functioning smoothly, but suddenly the styles I had defined were no longer appearing as intended in components ...

What is the process for sending an image as input to a Django view using an Angular frontend?

I currently have a django web api with an angular frontend that allows users to upload and view images. My goal now is to expand this functionality: when the user clicks the "segment" button (see image), it should send the corresponding image to my python ...

What is the best way to format specific text as bold within an input text field?

I am attempting to make certain text bold within an input text field. However, I'm uncertain about how to achieve this because HTML code is not recognized inside a text field. Therefore, using <b> will not be effective. Is there a way to bold sp ...

CRITICAL ERROR: CALL_AND_RETRY_LAST Unable to allocate memory - JavaScript heap exhausted while in production mode

Last week in production, I kept encountering a persistent issue: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory. Despite attempting to increase the HEAP size, my efforts were ineffective. Since this problem is affecting ...

What is the best way to transfer a file from Postman to a Node.js server using Multer?

Windows Express version 4.12.4 Multer version 1.0.1 Node version v0.10.22 I'm currently working on sending a file to my node.js server using Postman. I'm following the instructions provided in the readme here This is what I am sending wi ...

"Unlocking the JSON element with jQuery Ajax: A step-by-step guide

I am trying to pinpoint a specific element within my JSON data: { "taskMeta": "Some meta info", "tasksLib": [ { "task001": { "id":"1", "createDate":"01.02.17", "dueDate":"02.03.17", "au ...

Exposing a Hidden Division with a Link via jQuery

I currently have a jQuery Panel set up to open when clicking a button. Now, I am looking to add a second link at the bottom of the page that will also open the same panel. Can anyone provide guidance on how to accomplish this? You can view my JSFiddle a ...

Issue with retrieving JSON data through HTTP Get request on Internet Explorer, while it works fine on

Trying to upgrade a basic weather plugin by integrating geolocation services that identify a user's location based on their IP address. Smooth sailing on Chrome and Firefox, but IE seems to be causing some trouble. Any idea what might be the issue wit ...

Javascript Library Issue: "Implicitly Declared Type 'Any' Error"

I am currently in the process of developing a JavaScript library that will interact with an API. My goal is to create a module that can be easily published on npm and utilized across various frameworks such as Angular or React. Below is the code snippet fo ...

Transform a PNG image with transparency into a JPEG file using imagemagick

Consider utilizing the imagemagick npm module for your image manipulation needs. In the task of converting a .png file with a transparent background to a .jpeg with a white background, you may encounter challenges. Here is an example: const ImageMagick ...