Chartjs-Chart.js not updating multiple charts independently

0👍

Currently, inside setInterval, you alternately update both charts with y-values 0 and 1. Instead of these values, use Match.random(), same as you do when you initialize the chart data.

setInterval(() => {
  for (let i = 0; i < graphs.length; i++) {
    graphs[i].updateData({
      first: [Math.random()],
      second: [Math.random()]
    })
  }
}, 1000)

Please take a look at your amended code below and see how it works.

window.addEventListener(`load`, () => {
  Chart.defaults.plugins.tooltip.enabled = false;
  let data = {
    labels: (() => {
      let arr = [];
      for (let i = 0; i < 31; i++) {
        arr.push((30 - i) * -2);
      }
      return arr;
    })(),
    datasets: [{
        label: `first`,
        data: (() => {
          let arr = [];
          for (let i = 0; i < 31; i++) {
            arr.push(Math.random())
          }
          return arr
        })(),
        borderColor: 'rgb(75, 192, 192)',
      },
      {
        label: `second`,
        data: (() => {
          let arr = [];
          for (let i = 0; i < 31; i++) {
            arr.push(Math.random())
          }
          return arr
        })(),
        borderColor: 'rgb(75, 0, 192)',
      }
    ]
  }
  let graphs = [];
  for (let i = 0; i < 2; i++) {
    graphs.push(new lineGraph(data, data.labels.length));
  }
  setInterval(() => {
    for (let i = 0; i < graphs.length; i++) {
      graphs[i].updateData({
        first: [Math.random()],
        second: [Math.random()]
      })
    }
  }, 1000)
})

function lineGraph(data, maxDataSize) {
  let div = document.createElement(`div`);
  div.classList.add(`module`, `module-line`);

  let canvas = document.createElement(`canvas`);
  canvas.classList.add(`canvas-line`);
  canvas.width = 200;
  canvas.height = 40;

  div.appendChild(canvas);
  this.div = document.body.appendChild(div);
  this.canvas = this.div.getElementsByClassName(`canvas-line`).item(0);
  this.ctx = this.canvas.getContext(`2d`);
  this.chart = new Chart(this.ctx, {
    type: `line`,
    data: data,
  })
  this.updateData = (data) => {
    this.chart.data.datasets.forEach((dataset, index) => {
      let newData = data[dataset.label];
      if (newData) {
        if (dataset.data.length >= maxDataSize) {
          for (let i = 0; i < (dataset.data.length - maxDataSize) + newData.length; i++) {
            dataset.data.shift();
          }
        }
        dataset.data.push(...newData);
      }
    });
    this.chart.update();
  }
  return this;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script>

Leave a comment