adrianhajdin/project_corona_tracker

TypeError: Cannot read property 'length' of undefined

rcapollari opened this issue · 6 comments

I keep getting a TypeError: Cannot read property 'length' of undefined when I run the code. This is my Chart.js:
`import React, {useState, useEffect } from 'react';
import {fetchDailyData} from '../api'
import { Line, Bar } from 'react-chartjs-2';
import styles from './Chart.module.css';

const Chart = () => {
const [dailyData, setDailyData] = useState({});

useEffect (() => {
    const fetchAPI = async () => {
        setDailyData(await fetchDailyData());
    }
    
    fetchAPI();
}, []);

const lineChart = (
    dailyData.length
        ? (
        <Line 
        data={{
            labels: dailyData.map(({ date }) => date),
            datasets: [{
                data: dailyData.map(({ confirmed }) => confirmed),
                label: 'Infected',
                borderColor: '#3333ff',
                fill: true,
            }, {
                data: dailyData.map(({ deaths }) => deaths),
                label: 'Deaths',
                borderColor: 'red',
                backgroundColor: 'rgba(255, 0, 0, 0.5)',
                fill: true,
            }],
        }}
    />) : null
);

return(
    <div className={styles.container}>
        {lineChart}
    </div>
);

}

export default Chart;And here is my index.js:import axios from 'axios';

const url = 'https://covid19.mathdro.id/api'

export const fetchData = async () => {
try {
const {data : {confirmed, recovered, deaths, lastUpdate}} = await axios.get(url);

    return {confirmed, recovered, deaths, lastUpdate};
} catch(error) {

}

}

export const fetchDailyData = async () => {
try {
const { data } = await axios.get('${url}/daily');

    const modifiedData = data.map((dailyData) => ({
        confirmed: dailyData.confirmed.total,
        deaths: dailyData.deaths.total,
        date: dailyData.reportDate,
    }));
    return modifiedData;
} catch(error) {

}

}`

Send me the github repo link. I'll check and revert back to you.

const { data } = await axios.get('${url}/daily');

I think it's because of the above line. You are not getting data because I think you need to use it like this:

const { data } = await axios.get(${url}/daily);

Let me know if it's fixed the problem.

Hi, the correct usage is const { data } = await axios.get(${url}/daily);

That should resolve the error!

Hi, the correct usage is const { data } = await axios.get(${url}/daily);

That should resolve the error!

Hi, I am also getting the same error.

while using const { data } = await axios.get(${url}/daily);
It is throwing Parsing error: Unexpected token, expected ","

@tanishgupta07 Try this:

const { data } = await axios.get(`${url}/daily`);

Note the use of backticks around "${url}/daily" to create a template string.

Hope that helps.