Skip to content
Advertisement

Old state is being shown despite updating in React Highcharts click event

I want the new state to show, but I get different behavior. I have three points (look at code below or sketch) and if I click a point, then whatever state value is at that time, in future clicks the old value is shown. I am not sure what this is being caused by.

For example: Click point A, then 0 is printed. Increment state, then click A, still 0 is printed. Click point B, 1 is printed. Click point A, still 0 is printed.

Sketch: https://stackblitz.com/edit/react-bwskb9?file=index.js

import React, { useState, useEffect } from "react";
import { render } from "react-dom";
import HighchartsReact from "highcharts-react-official";
import Highcharts from "highcharts";

const LineChart = () => {
  const [hoverData, setHoverData] = useState(null);
  const [someState, setSomeState] = useState(0);
  const [chartOptions, setChartOptions] = useState({
    xAxis: {
      categories: ["A", "B", "C"]
    },
    series: [{ data: [1, 2, 3] }],
    plotOptions: {
      series: {
        point: {
          events: {
            click(e) {
              console.log(someState);
              setHoverData(e.point.category);
            }
          }
        }
      }
    }
  });

  const updateSeries = () => {
    setChartOptions({
      plotOptions: {
        series: {
          point: {
            events: {
              click(e) {
                console.log(someState);
                setHoverData(e.point.category);
              }
            }
          }
        }
      }
    });
  };

  useEffect(() => {
    updateSeries();
  }, [someState]);

  return (
    <div>
      <HighchartsReact highcharts={Highcharts} options={chartOptions} />
      <h3>Clicked over {hoverData}</h3>
      <button onClick={() => setSomeState(val => val + 1)}>Incr</button>
      <p>{someState}</p>
    </div>
  );
};

render(<LineChart />, document.getElementById("root"));

Advertisement

Answer

Apparently, this is not something that is a problem in HighchartJS, but React hooks in particular. I solved this by using refs.

Refer here: How To Solve The React Hook Closure Issue?

Advertisement