1
try moving everything into useEffect like this.
do not mix state and "let" variables.
I’m not sure what these 2 functions do, but it’s not advisable to those variables inside the function.
confirmedChart();
deathChart();
try these.
const Chart = ({ CountryName }) => {
const [data, setData] = useState({});
const activeChart = (caseDatesSubstracted) => {
//if u want to separate, then pass in the arg.
setData({ .... }) // now u can use caseDatesSubstracted here.
}
useEffect(() => {
const loadData = async() => {
await fetch(`https://api.covid19api.com/total/dayone/country/${CountryName}`)
.then(response => response.json())
.then(data => {
//do not declare them outside useEffect as they get re-initialize on every render.
let caseDate = [];
let active = [];
let confirmed = [];
let deaths = [];
let caseDatesSubstracted = [];
for (const dataObj of data) {
console.log(data)
caseDate.push(dataObj.Date);
active.push(dataObj.Active);
confirmed.push(dataObj.Confirmed)
deaths.push(dataObj.Deaths)
}
for (let i = 0; i < caseDate.length; i++) {
caseDatesSubstracted.push(caseDate[i].substring(0, caseDate[i].length - 10));
}
//set ur state here.
/* alternatively, use activeChart(caseDatesSubstracted) by passing in the variable */
setData({
labels: caseDatesSubstracted,
datasets: [{
label: 'Active Cases',
data: active,
backgroundColor: [
['black']
],
}]
})
})
}
loadData();
confirmedChart(); //not good, move them. follow what I did for activeChart()
deathChart(); // not good, move them. follow what I did for activeChart()
}, []);
}
Source:stackexchange.com