Abed Aarabi
Abed Aarabi

Reputation: 149

React chartsJS streaming live data

I am trying to build a React ChartsJS live data streaming using Chartjs i managed to render the canvas on the page but for some reason, I still can't make move like a live line chart data I am not sure if I need to embed anything to the HTML page. i install those packages: chart.js "chartjs-adapter-luxon": "^1.1.0 "chartjs-plugin-streaming": "^2.0.0" I hope someone could help me!

import React from "react";
import { Line } from "react-chartjs-2";
import Chart from "chart.js/auto";
import { StreamingPlugin, RealTimeScale } from "chartjs-plugin-streaming";
Chart.register(StreamingPlugin, RealTimeScale);

export const IotChart = () => {
  const data = {
    datasets: [
      {
        label: "Dataset 1",

        fill: false,
        lineTension: 0.4,
        backgroundColor: "#f44336",
        borderColor: "#f44336",
        borderJoinStyle: "miter",
        pointRadius: 0,
        showLine: true,
        data: [] as any,
      },
    ],
  };

  const options = {
    scales: {
      xAxes: [
        {
          type: "realtime",
          realtime: {
            onRefresh: function () {
              data.datasets[0].data.push({
                x: Date.now(),
                y: Math.random() * 100,
              });
            },
            delay: 300,
            refresh: 300,
          },
        },
      ],
      yAxes: [
        {
          scaleLabel: {
            display: true,
            fontFamily: "Arial",
            labelString: "Moment",
            fontSize: 20,
            fontColor: "#6c757d",
          },
          ticks: {
            max: 100,
            min: 0,
          },
        },
      ],
    },
  } as any;

  return (
    <div>
      <div>
        <Line data={data} options={options} width={400} height={200} />
      </div>
    </div>
  );
};

enter image description here

Upvotes: 2

Views: 4090

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31351

This is because you define your scales as arrays instead of objects. This is changed in V3, for all the changes please read the migration guide because there are a lot more breaking changes, for example your Y axis scale label font declaration.

If you check the streaming documentation/examples you would also see that its defined as objects.

So changing to this will fix your issue:

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

Upvotes: 2

Related Questions