[Chartjs]-Graph streaming real-time data with react and chartjs

2👍

The data format you provided is wrong, you are trying to

data.dataset.data.push but the data you provided only have X value. you need to reformat it, the data should have the format like this: {x:$(value), y:${value}}

Open the code snippet below in CodeSandbox

import React from "react";
import { Line } from "react-chartjs-2";
import "chartjs-plugin-streaming";
var createReactClass = require("create-react-class");

const data = {
  datasets: [
    {
      label: "Dataset 1",
      borderColor: "rgb(255, 99, 132)",
      backgroundColor: "rgba(255, 99, 132, 0.5)",
      lineTension: 0,
      borderDash: [8, 4],
      data: []
    }
  ]
};

const options = {
  scales: {
    xAxes: [
      {
        type: "realtime",
        realtime: {
          onRefresh: function() {
            data.datasets[0].data.push({
              x: Date.now(),
              y: Math.random() * 100
            });
          },
          delay: 2000
        }
      }
    ]
  }
};

export default createReactClass({
  displayName: "LineExample",
  render() {
    return (
      <div>
        <Line data={data} options={options} />
      </div>
    );
  }
});

1👍

without a snippet to play with I’d guess that the problem is here

onRefresh: function(chart) {
  data.dataset.data.push({
    x: Date.now(),
    y: Math.random()
  });
}

you’ve pushed the new data to the initial dataset, but at a guess you’ll need to push it to the chart itself. looking at the example at:

https://nagix.github.io/chartjs-plugin-streaming/samples/bar-horizontal.html

seems like you should be passing the data directly to the chart

chart.config.data.datasets.forEach(function(dataset) {
  dataset.data.push({
    x: Date.now(),
    y: randomScalingFactor()
  });
});

or maybe, (again I’m just guessing where the new data might go without a mvp example to play with, console.log out the chart variable in the onRefresh callback to find the right location), If you setup a mvp on somewhere like stackblitz I/someone can update this answer.

onRefresh: function(chart) {
  chart.dataset.data.push({
    x: Date.now(),
    y: Math.random()
  });
}

0👍

chart is undefined because it was never defined in React.

Here is an example with React:

onRefresh: function(chart) {
   chart.dataset.data.push({
   x: Date.now(),
   y: Math.random()
  });
}

Leave a comment