Reputation: 1541
Dataset: https://disease.sh/v3/covid-19/historical/usa?lastdays=all
I am newer to React and am trying to get my feet wet with a COVID-19 Tracker so bear with me... I am trying to access Timeline > Cases from the above dataset but can't seem to make it work. I've tried let date in data.timeline.cases
however that doesn't work either. Maybe i'm looking in the wrong spot - looking for some guidance. Thanks!
const buildChartData = (data, casesType) => {
let chartData = [];
let lastDataPoint;
for (let date in data.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data[casesType][date] - lastDataPoint,
}
chartData.push(newDataPoint);
}
lastDataPoint = data[casesType][date];
}
return chartData;
};
function LineGraph({ casesType = 'cases' }) {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async() => {
await fetch('https://disease.sh/v3/covid-19/historical/usa?lastdays=120')
.then((response) => {
return response.json()
})
.then(data => {
let chartData = buildChartData(data, casesType);
setData(chartData);
});
};
fetchData();
}, [casesType]);
Upvotes: 0
Views: 117
Reputation: 10498
Ok, as you said you tried with let date in data.timeline.cases
but you need to change the other part of code too.
It s not data[casesType]
but data.timeline[casesType]
for (let date in data.timeline.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data.timeline[casesType][date] - lastDataPoint,
}
chartData.push(newDataPoint);
}
lastDataPoint = data.timeline[casesType][date];
}
Upvotes: 2