0
import Error from 'next/error'
import React, { useState, useEffect } from 'react'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'

function id() {

    const [count, setCount] = useState()

    const options = {

        chart: {
            renderTo: 'chart',
            type: 'spline',
            zoomType: 'x',
            backgroundColor: 'transparent',
            plotBorderColor: 'transparent',
            events: {
                load: function () {
                    const chart = this
                    setInterval(function () {
                        chart.series[0].addPoint([new Date().getTime(), count], true)
                    }, 1000);
                }
            }
        },
        title: {
            text: 'Chart'
        },
        xAxis: {
            type: 'datetime',
            tickPixelInterval: 200,
            gridLineColor: "red",
            labels: {
                style: {
                    color: "red"
                }
            },
            lineColor: "red",
            minorGridLineColor: 'red',
            tickColor: "red",
            title: {
                style: {
                    color: "red"
                }
            }
        },
        yAxis: {
            title: {
                text: ''
            },
            gridLineColor: "red",
            labels: {
                style: {
                    color: "red"
                }
            },
            lineColor: "red",
            minorGridLineColor: 'red',
            tickColor: "red"
        },
        credits: {
            enabled: false
        },

        series: [{
            name: "Random Number"
        }]
    }

    useEffect(() => {

        const interval = setInterval(async () => {

            const res = await fetch("https://socialcounts.herokuapp.com/https://socialcounts.in/api/random-num")

            const data = await res.json()

            setCount(data["num"])
        }, 1000);

        return () => clearInterval(interval);

    }, [])

    return (<center>
        <h1>{count}</h1>
        <p></p>
        <HighchartsReact highcharts={Highcharts} options={options} />
    </center>)
}

export default id

Hi, I'm doing with a next js project.

I need to add the highcharts graph in my project.
I want to get the data from api & push it to setCount hook. but, I'm getting problem.. whenever I want to get the value of count hook in chart.series[0].addPoint([new Date().getTime(), count],true) but i can't able to get the updated value from my hook. I can't get the updated value of const [count, setCount] = useState() variable from

events: {
    load: function () {
        const chart = this
        setInterval(function () {
            chart.series[0].addPoint([new Date().getTime(), count], true)
        }, 1000);
    }
}

I think, I'm getting This problem because of setInterval function.. but setInterval is important, else how can I push data to chart.series[0].addPoint with interval.
How can i get the updated value in every setInterval.

Please help me..

Munny Reol
  • 41
  • 7

1 Answers1

2

Please check this great explanation about values in useState: https://stackoverflow.com/a/58877875

The value might be different between 2 renders, but remains a constant inside the render itself and inside any closures (functions that live longer even after render is finished, e.g. useEffect, event handlers, inside any Promise or setTimeout).

As a solution use addPoint method in the same function where you recieve data.

function App() {
  const [count, setCount] = useState();
  const chartComponent = useRef(null);
  const [options] = useState({...});

  useEffect(() => {
    const interval = setInterval(async () => {
      const res = await fetch(
        "https://socialcounts.herokuapp.com/https://socialcounts.in/api/random-num"
      );

      const data = await res.json();
      if (chartComponent.current) {
        chartComponent.current.chart.series[0].addPoint(
          [new Date().getTime(), data["num"]],
          true
        );
      }

      setCount(data["num"]);
    }, 2000);

    return () => clearInterval(interval);
  }, []);

  return (
    <center>
      <h1>{count}</h1>
      <HighchartsReact
        ref={chartComponent}
        highcharts={Highcharts}
        options={options}
      />
    </center>
  );
}

Live demo: https://codesandbox.io/s/highcharts-react-demo-forked-x9xi9?file=/demo.jsx

ppotaczek
  • 36,341
  • 2
  • 14
  • 24
  • hello, I can't able to remove and redraw the chart. here is the codesandbox project. https://codesandbox.io/s/sad-fire-lms4nq – Munny Reol Sep 25 '22 at 15:42
  • 1
    Hi @Munny Reol, Please create a new question with a more detailed description of the problem and also with `highcharts` tag. – ppotaczek Sep 26 '22 at 08:48