Chartjs-Chart.js – How to update chart data with interval

1👍

It looks like it’s not appearing to update because you’re calling your data and storing in a variable which, from the scope of the application had not changed.

If you move your data request to a function and then call that from the initialising code and within setInterval you should see your data being updated freshly with each call to the function getData.

Here’s a version of your code with what I mean, where getData() is used instead of datapoints:

const getData = () => {
  console.log('Requesting data')
  const totalRunTime = current_array.MTConnectStreams.Streams.DeviceStream.ComponentStream[12].Samples.DynamicBasicData[1];
  const totalTimeRemaining = current_array.MTConnectStreams.Streams.DeviceStream.ComponentStream[12].Samples.DynamicBasicData[13];
  const timeRemaining = ((totalTimeRemaining / totalRunTime) * 100)
  return [(100 - timeRemaining), timeRemaining]
}

const data = {
  datasets: [{
      data: getData(),
      backgroundColor: ['rgba(20, 121, 255, 0.7)', 'rgba(208, 208, 208, 0.5)'],
      borderWidth: 1,
      cutout: '70%'
  }]
};

const counter = {
  id: 'counter',
  beforeDraw( chart, args, options ) {
    const { ctx, chartArea: { top, right, bottom, left, width, height } } = chart;
    ctx.save();

    ctx.font = options.fontSize + 'px ' + options.fontFamily;
    ctx.textAlign = 'center';
    ctx.fillStyle = options.fontColor;
    ctx.fillText(getData()[0].toFixed(3) + '%', width / 2, (height / 2) + (options.fontSize * 0.34));
  }
};

const config = {
  type: 'doughnut',
  data,
  options: {
    plugins: {
      legend: {
        display: false
      },
      tooltip: {
        enabled: false
      },
      counter: {
        fontColor: '#193b68',
        fontSize: '16',
        fontFamily: 'Sofia Pro Medium'
      }
    }
  },
  plugins: [counter]
};

const doughnutChart = new Chart(
  document.getElementById('chart'),
  config
);

setInterval(function addData(chart, data) {
  console.log('updating', Date.now())
  doughnutChart.data.datasets.forEach((dataset) => {
      dataset.data = getData();
  });
  doughnutChart.update('none');
  }, 2000
);

Here’s a codepen of an updating version but with random values used instead of your data requests.

This might be the problem and I hope this helps you.

One tip is to use console.log to see what’s being called and placing your code in functions can make it easier to debug too by seeing where and when it is being called by using console.log or debugger.

Leave a comment