chartjs-plugin-dragdata
chartjs-plugin-dragdata copied to clipboard
BUG: onDrag cannot read the updated series data
Describe the bug @chrispahm I want to bound a datapoint within a range of its current value (e.g. +/-0.5) upon dragging (e.g. if the point is 1.5, it's bounded at (1.0, 2.0), if the point is 1.0, then it's bounded at (0.5, 1.5))
To achieve this, I use useState
to initialise the series data (i.e. series
). In onDrag
callback, I make use of series
to access the value before it's dragged. In onDragEnd
, I update series
by setSeries
to make sure the state is sync with what the chart is showing.
Here is my brief code snippet:
const initSeries = [1, 3.5, 5, 2.8];
const [series, setSeries] = useState(initSeries);
// omit the details
...
onDrag: (e, datasetIndex, index, value) => {
// for debugging
console.log("series: ", series);
if (value < series[index] - 0.5 || value > series[index] + 0.5) {
return false;
}
}
onDragEnd: (e, datasetIndex, index, value) => {
setSeries((arr) =>
arr.map((x, xIndex) => (xIndex === index ? value : x))
);
}
However, it is not working as expected because I see series
within onDrag
is not properly updated after some drags. But I am sure series
has been updated, as verified in my sample code below.
To Reproduce Here is my PoC code to reproduce the issue: https://codesandbox.io/s/draggablelinecharts-5dxk97?file=/src/App.js