Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading 'map') with ChartJs

I’m facing this issue while trying to create a donut chart using react-chartjs-2. I used console.log() to test whether every array had a value, and every single array returned values they are supposed to. I also tried rewriting the code using for loops instead of map() to make sure it’s not the problem. I tried loading only this component to make sure no other component is generating the problem.

You see here a reproduction of the same error, using minimalistic code, thanks:
https://codesandbox.io/s/sleepy-glitter-5tqjr9?file=/src/SalesDoughnutChart.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The initial state for chartData is empty, which means the datasets value isn’t available on the very initial rendering.

To get around of this issue, you can initialize the chartData state with empty datasets array as how the v4 version of the example code does —

  const [chartData, setChartData] = useState({
    datasets: []
  });

See the example from official documentation here: https://react-chartjs-2.netlify.app/docs/migration-to-v4/#drawing-charts-with-gradients

For your follow-up question about arc not a register element, you need the follow code to "register" to ChartJS for them to know what you are using —

import {Chart, ArcElement} from 'chart.js'
Chart.register(ArcElement);

Read more about registering the element here: https://react-chartjs-2.netlify.app/faq/registered-element

Your codesandbox but the working version here – https://codesandbox.io/s/vigilant-kapitsa-plyzfj?file=/src/SalesDoughnutChart.js:206-275

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading