Several charts have been implemented, and we want to dynamically output a new chart every time the button is pressed. However, it says that the chart cannot be drawn because a chart with a specific ID currently exists. How do I resolve these errors? Is there any way to fix the error without destroying the implemented chart? Below is my code.
const main = () =>
{
const [count, setCount] = useState([])
const addWidget = () =>
{
setCount([...count, data])
}
const data=
{
labels: ['1', '2', '3', '4', '5', '6', '7' , '8', '9','10'],
datasets: [
{
type: 'line',
label: 'Dataset 1',
borderColor: 'rgb(54, 162, 235)',
borderWidth: 2,
data: [30, 9, 24, 50,-20,20, 17, 45, 49],
}
],
}
return (
<div>
// chart test code
<Chart data = {Line_data1} options={options} style={{ position: "relative"}}/>
<Chart data = {Bar_data} options={Bar_mutilLabel_options} style={{ position: "relative"}}/>
{count.map(el => <><div><Chart style={{width:'10%'}} options={options} data={el}/></div></>)}
<button onClick={addWidget}>
Click me
</button>
</div>
)
}
Check out this thread in react-chartjs-2' issues. Specifically MartinP-C's comment.
I was getting this error (again with React 18.0.1, in Strict Mode) Removing Strict Mode stops the error (because Strict Mode double-invokes lifecycle functions when in dev mode? Hence re-use of canvas? https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)
However! Strict Mode wasn't the problem itself. I had not registered a Chart.JS component and the error being thrown ('"arc" is not a registered element') must have caused React to double-invoke and try to re-use the canvas.
Fixing the registered element error also stopped "Canvas already in use" error. (Registering components: https://react-chartjs-2.js.org/docs/migration-to-v4#tree-shaking)