I’m trying to use the react wrapper of chart.js and I’m having an issue. When I’m trying to add a chart, there is an error (” TypeError: Cannot read property ‘defaults’ of undefined”)
The code is the following:
import React, { useState, useEffect } from 'react'; import api from '../../services/API'; import './Graph.css'; import { Line } from 'react-chartjs-2'; export default function Graph() { const [dataChart, setDataChart] = useState({ }); useEffect(() => { const abortController = new AbortController(); const signal = abortController.signal; const getData = async() => { let confirmedCases = []; let dateOfCases = []; await api.get('btt-prices', {signal: signal}) .then ( resp => { for (const dataObj of resp.data ) { console.log( dataObj ) confirmedCases.push(dataObj.price); let tempDate = new Date (dataObj.date); dateOfCases.push(tempDate.getUTCDate()); } }); setDataChart({ labels: dateOfCases, datasets: [{ label: 'Confirmed cases', data: confirmedCases }] }); //console.log(dataChart) } getData(); return () => { abortController.abort(); } }, []); return( <div className='container'> <Line data={ dataChart }/> </div> ); }
The error that shows is the following:
TypeError: Cannot read property 'defaults' of undefined (anonymous function) C:/Users/e/Desktop/test/front/node_modules/react-chartjs-2/es/index.js:643 640 | }(_react["default"].Component); 641 | 642 | exports.Scatter = Scatter; > 643 | var defaults = _chart["default"].defaults; 644 | exports.defaults = defaults;
I tried to search about it but I can’t see any solution… I tried to install again chartjs (besides react-chartjs) just in case, but the error still remains. How can I solve this error Thank you!
Answer
Which version of chart.js are you running because if you reinstalled it its a high chance you are running version 3 of the lib which is at the moment still not compatible with the wrapper so you will have to install the latest version 2 release of chart.js (2.9.4)