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
JavaScript
x
60
60
1
import React, { useState, useEffect } from "react";
2
import { render } from "react-dom";
3
import HighchartsReact from "highcharts-react-official";
4
import Highcharts from "highcharts";
5
6
const LineChart = () => {
7
const [hoverData, setHoverData] = useState(null);
8
const [someState, setSomeState] = useState(0);
9
const [chartOptions, setChartOptions] = useState({
10
xAxis: {
11
categories: ["A", "B", "C"]
12
},
13
series: [{ data: [1, 2, 3] }],
14
plotOptions: {
15
series: {
16
point: {
17
events: {
18
click(e) {
19
console.log(someState);
20
setHoverData(e.point.category);
21
}
22
}
23
}
24
}
25
}
26
});
27
28
const updateSeries = () => {
29
setChartOptions({
30
plotOptions: {
31
series: {
32
point: {
33
events: {
34
click(e) {
35
console.log(someState);
36
setHoverData(e.point.category);
37
}
38
}
39
}
40
}
41
}
42
});
43
};
44
45
useEffect(() => {
46
updateSeries();
47
}, [someState]);
48
49
return (
50
<div>
51
<HighchartsReact highcharts={Highcharts} options={chartOptions} />
52
<h3>Clicked over {hoverData}</h3>
53
<button onClick={() => setSomeState(val => val + 1)}>Incr</button>
54
<p>{someState}</p>
55
</div>
56
);
57
};
58
59
render(<LineChart />, document.getElementById("root"));
60
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?