0

I am using react hooks to create chart using chartjs. With the help of socket.io, the webapp is receiving data from a nodejs server. The data gets successfully added to temp and time array, but unfortunately i am unable to update the chart everytime new data comes.

import React,{useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';
import {Line} from 'react-chartjs-2';
import io from 'socket.io-client'
const socket = io('http://localhost:5000');

function App() {
  const [chartData, setChartData] = useState({});
  const [dataReact, setData] = useState({});
  var temp =[];
  var time = [];
  const chart = ()=>{
    setChartData({
      labels: time,
        datasets: [{
            label: '# of Votes',
            data: temp,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    })
  }

  useEffect(()=>{
    socket.on('data1', res => {

      console.log(res);
      temp.push(res.IotData.temperature);
      time.push(res.MessageDate);
      });
    chart();

  },[])

  return (
    <div className="App">
      <Line data={chartData}/>
    </div>
  );
}

export default App;
ForgottenTale
  • 35
  • 1
  • 6

2 Answers2

0

In useEffect() the second parameter (i.e. the []) which is an array of properties to be observed within the scope of the stateless component. Whenever any of them are updated, the function is executed again. So add chart into the empty array.

yudhiesh
  • 6,383
  • 3
  • 16
  • 49
0

Also don't forget to put redraw parameter in your chart:

<Line data={chartData} redraw={true}/>

This will allow the chart to update and be redrawn.

Stan
  • 1