Sending fetchDailyData API response to Chart.jsx (using different API)
kortstin opened this issue · 4 comments
Hello! I am following through your tutorial on this tracker, but decided to use a different API as practice on consuming different kinds of datasets. I seem to have hit a wall though when it comes to handling data in fetchDailyData() in index.js, and also retrieving this data in a similar way as you to be used in the Line Chart.
I am using the following API path for fetchDailyData (global):https://corona.lmao.ninja/docs/?urls.primaryName=version%202.0.0#/JHUCSSE/get_v2_historical_all
My code is below:
index.js
export const fetchDailyData = async () => {
try {
const { data } = await axios.get(`${url}/historical/all`);
const labels = Object.keys(data.cases);
const cases = labels.map((name) => data.cases[name]);
const deaths = labels.map((name) => data.deaths[name]);
const recovered = labels.map((name) => data.recovered[name]);
} catch (error) {
return error;
}
}
Chart.jsx
import React, {useState, useEffect} from 'react';
import { Line, Bar } from 'react-chartjs-2';
import {fetchDailyData} from '../../api';
import styles from './Chart.module.css';
const Chart = () => {
const [dailyData, setDailyData]= useState([]);
useEffect(() => {
const fetchAPI = async () => {
setDailyData(await fetchDailyData());
}
fetchAPI();
});
const lineChart = (
<Line
/>
);
return(
<div className = {styles.container}>
{lineChart}
</div>
);
};
export default Chart;
On index.js, in your try {}
Isn't the API /v2/historical/all
Is it missing the v2?
What does the console.log display on your console? That should help, is it udnefined, or show something else.
Oh no it has the v2 in the base url. The console log displays an object of objects of cases(infected), deaths, and recovered. I wanted to keep it as close to yours as possible.
API response looks like:
{ cases:{ key:value}, deaths:{ key: value}, etc....
The keys are dates and the values are the numbers on that dates.
Would you be able to help me transfer data to the chart keeping the structure as close to yours as possible?
Have you tried using the filter method to filter the current date from the object list you get back?
Or you can just 'pop off', use the latest value in the corresponding object lists {"date": value}
Notice in the original tutorial the API responded back with one value for confirmed, recovered, deaths.
The API you're using brings back the counts for the last 30 days or whatever query of last days put in.
Resource: MDN web doc Array.prototype.filter()
Hey I was actually able to separate the keys and assign them to a label constant, and do the same for cases, recovered, and deaths assigning them to variables too? I have updated the code above. Can you help me with moving these variables over to Chart.jsx?