Issue with Vue-ChartJS where adding datasets does not refresh the chart display

I am currently utilizing Vue-ChartJS to showcase a chart on my website. However, I have encountered an issue when trying to update the datasets using the Push Function - the chart does not update as expected (even though it should according to the documentation). Interestingly, directly setting the reactive variable does update the chart successfully (e.g., this.transaction = Object). While the current ChartComponent is functioning in this manner, I aim to retrieve data from an API and incorporate it into the view.

LineChart.js

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

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options'],

  mounted () {
    this.renderChart(this.chartData,  this.options)
  }
}

ChartComponent.vue (utilizing direct set)

<template>
<div class="card">
    <div class="card-header">

      Statistics

      <div class="float-right">
        <form method="POST" class="form-inline">
          <div class="form-group mx-sm-2 mb-2">
            <button type="button" v-on:click="updateChart('week')" class="btn btn-primary">Week</button>
          </div>
          <div class="form-group mx-sm-2 mb-2">
            <button type="button" v-on:click="updateChart('month')" class="btn btn-primary">Month</button>
          </div>
          <div class="form-group mx-sm-2 mb-2">
            <button type="button" v-on:click="updateChart('year')" class="btn btn-primary">Year</button>
          </div>
          <div class="form-group mx-sm-2 mb-2">
            <label for="custom_from" class="mx-sm-2">From:</label>
            <input id="custom_form" type="date" class="form-control" />
          </div>
          <div class="form-group mx-sm-2 mb-2">
            <label for="custom_to" class="mx-sm-2">To:</label>
            <input id="custom_to" type="date" class="form-control" />
          </div>
        </form>
      </div>
    </div>
    <div class="card-body p-0">
      <div class="p-4">
        <line-chart :options="options" :chart-data="transactions"></line-chart>
      </div>
    </div>
  </div>
</template>

import LineChart from './LineChart.js'

export default {
  components: {
    LineChart
  },
  data () {
    return {
      transactions: {},
      options: {
        maintainAspectRatio: false,
        responsive: true,
        legend: {
          display: true
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    }
  },
  mounted () {
    this.fillData()
  },
  methods: {
    fillData () {
      this.transactions = {
        labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        datasets: [{
          label: 'Users',
          data: [12, 19, 3, 5, 2, 3, 20, 33, 23, 12, 33, 10],
          backgroundColor: 'rgba(66, 165, 245, 0.5)',
          borderColor: '#2196F3',
          borderWidth: 1
        }]
      }
    },
    updateChart (period) {
      console.log('Chart updated for period: ' + period);
      this.transactions = {
        labels: ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"],
        datasets: [{
          label: 'Users',
          data: [12, 19, 3, 5, 2, 3, 20, 33, 23, 12, 33, 10],
          backgroundColor: 'rgba(66, 165, 245, 0.5)',
          borderColor: '#2196F3',
          borderWidth: 1
        }, {
          label: 'Users',
          data: [123, 19, 3, 5, 2, 3, 20, 33, 23, 12, 33, 10],
          backgroundColor: 'rgba(66, 165, 245, 0.5)',
          borderColor: '#2196F3',
          borderWidth: 1
        }]
      }
      console.log(this.transactions)
    }
  },
}

ChartComponent.vue (utilizing push function)

import LineChart from './LineChart.js'

export default {
  components: {
    LineChart
  },
  data () {
    return {
      transactions: {},
      options: {
        maintainAspectRatio: false,
        responsive: true,
        legend: {
          display: true
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    }
  },
  mounted () {
    this.fillData()
  },
  methods: {
    fillData () {
      this.transactions = {
        labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        datasets: [{
          label: 'Users',
          data: [12, 19, 3, 5, 2, 3, 20, 33, 23, 12, 33, 10],
          backgroundColor: 'rgba(66, 165, 245, 0.5)',
          borderColor: '#2196F3',
          borderWidth: 1
        }]
      }
    },
    updateChart (period) {
      console.log('Chart updated for period: ' + period);
      this.transactions.datasets.push({
        label: 'Users',
        data: [123, 19, 3, 5, 2, 3, 20, 33, 23, 12, 33, 10],
        backgroundColor: 'rgba(66, 165, 245, 0.5)',
        borderColor: '#2196F3',
        borderWidth: 1
      });
      console.log(this.transactions)
    }
  },
}

Answer №1

One potential issue could be related to Vue reactivity. To ensure Vue reacts properly, update all references to this.transactions

updateChart(period) {
  console.log('Chart updated for period: ' + period);
  this.transactions.datasets.push({
    label: 'Users',
    data: [123, 19, 3, 5, 2, 3, 20, 33, 23, 12, 33, 10],
    backgroundColor: 'rgba(66, 165, 245, 0.5)',
    borderColor: '#2196F3',
    borderWidth: 1
  });
  this.transactions = JSON.parse(JSON.stringify(this.transactions))
}

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

Navigating with AngularJS Routes

I'm facing some issues with setting up routes in my Angular application. The main template displays correctly, but when I click on the link for another template, nothing happens. Below is a snippet of my code: INDEX.HTML <!DOCTYPE html> <ht ...

Displaying a list in Angular 2/4 without keeping track of any modifications

Is there a way to display a list of strings without tracking changes? (I'm experiencing performance issues). Fetching a list of languages from a REST API and then dynamically generating dropdowns for each language using *ngFor is causing the app to s ...

What is the best approach to add additional functionality to an already existing object method?

Let's say we have an obj, var obj = { l:function(){ alert(1); } } In what way can additional functionality be incorporated into obj.l without directly modifying the object? ...

AngularJS - Retaining the initial value without submitting

On the left side, I have a list of users with corresponding details displayed on the right. The form handles the details on the right using inputs with ng-model. Whenever I click on a user from the left section, the selected user changes and the model auto ...

Is there a way to asynchronously load multiple textures in three.js using a callback function?

Bringing in a single texture with a callback is a simple task, for instance: var loader = new THREE.TextureLoader(); var texture1 = loader.load("https://i.imgur.com/UiTMJzv.png", process); //executed only once texture1 is loaded function process(){ } B ...

Passing data from a parent node to a child node using JavaScript and the D3.js library

Creating a legend (var legend) for my d3js chart involves binding data to the parent 'g' element, specifically a string (label) that is needed in the child 'text' element. Any ideas on how to assign the parent data from the 'g&apo ...

Show an array of objects in a table using React

I'm working with an array of objects and need to display them in a table. However, I'm facing difficulties in showing the adjustedAmount, paidAmount, and cost type. Here's the object I'm dealing with: const datdfa = [ { index: 500, ...

Encountered an issue while importing React with webpack: Unable to resolve module 'react'

I keep encountering an issue Error: Cannot resolve module 'react' (and react-dom) while using webpack. This project setup seems to be the most challenging one I've faced, and I'm struggling to figure out why it's not functioning pr ...

Is there a way to postpone the collapse functionality in Bootstrap?

Is there a way to delay the display of collapsed elements in Bootstrap 4? For instance, how can you postpone the content of a Link href button from appearing in the example provided below? <p> <a class="btn btn-primary" data-toggle="collapse" ...

Tips for updating this.state once the server goes offline

As a newcomer to React, I have been researching my question about dealing with server offline situations. My setup involves a server storing an array of student information, which is then rendered on the page when the server is online. However, I'm st ...

The function chrome.notifications.create() is producing incorrect notification IDs upon clicking

Greetings for my first post here. I've been struggling with an issue in a personal project lately. I remember coming across a similar topic on this forum before, but now I can't seem to find it. As far as I recall, the question went unanswered. ...

I am in search of a method to rephrase the content while minimizing redundancy

I am looking to improve the code for handling two different conditions in the UI. Can someone suggest a better way to rewrite it? <i *ngIf="measures.length > 0"> <ul *ngFor="let m of measures"> <io-data-selection-row [text] ...

Enhance Your Website with Bootstrap 4 Card Image Zoom

Is it possible to add an image zoom effect to Bootstrap 4 cards? I found some inspiration at . Below are the codes I have used: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha ...

Utilizing Vue and Typescript for efficient dependency injection

After attempting to use vue-injector, I encountered an issue as it was not compatible with my version of Vue (2.6.10) and Typescript (3.4.5). Exploring other alternatives, there seem to be limited options available. Within the realm of pure typescript, t ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

How can you store JavaScript objects to files, including their methods, in a Node.js environment?

In reading about saving objects to files in Node.js here on Stack Overflow, I understand the process. However, I am curious if there is a method that allows for writing an object in a manner that would enable me to reload the object into memory along wit ...

Sharing information from one component to another in ReactJS can be achieved by using props or the context API. By

There are two important files - Sidebar and UserDataElements. The goal is to showcase the data from UserDataElements in the Sidebar. Here's what I've attempted so far: This is the primary file where both files are being fetched. <Sidebar&g ...

Ways to modify input value based on another input in VueJS

Two sets of text boxes are displayed in a grid format, which can be viewed here. The objective is for users to fill out the top boxes and have the values automatically update as they fill out the corresponding bottom boxes. For example, if you input 100 i ...

The dark theme in React Material UI will be specifically targeted and applied only to the drawer

I want to implement a dark theme specifically for the drawer component. In Drawer.js <ThemeProvider theme={theme}> <div> {props.token && ( <Drawer anchor="left" open={props.isDrawerOpen} ...

Select component with nested checkboxes for multilevel dropdown

I am interested in developing nested dropdowns with checkboxes, similar to the example shown in this image: Image 1 Is there a way to achieve this functionality using React? I have not been able to find any specific library that allows for this implement ...