0

My Object

const globalData = {
    "confirmed": {
        "value": 106643519,
        "detail": "https://covid19.mathdro.id/api/confirmed"
    },
    "recovered": {
        "value": 59549395,
        "detail": "https://covid19.mathdro.id/api/recovered"
    },
    "deaths": {
        "value": 2330839,
        "detail": "https://covid19.mathdro.id/api/deaths"
    },
    "dailySummary": "https://covid19.mathdro.id/api/daily",
    "dailyTimeSeries": {
        "pattern": "https://covid19.mathdro.id/api/daily/[dateString]",
        "example": "https://covid19.mathdro.id/api/daily/2-14-2020"
    },
    "image": "https://covid19.mathdro.id/api/og",
    "source": "https://github.com/mathdroid/covid19",
    "countries": "https://covid19.mathdro.id/api/countries",
    "countryDetail": {
        "pattern": "https://covid19.mathdro.id/api/countries/[country]",
        "example": "https://covid19.mathdro.id/api/countries/USA"
    },
    "lastUpdate": "2021-02-09T17:23:36.000Z"
}

I want to access "value" from the "confirmed" key. How can I do that...? I have tried doing this

function Cards() {

   const [globalData, setGlobalData] = useState({});

   useEffect(() => {
    async function getData(){
        const response = await fetch("https://covid19.mathdro.id/api")
        const data = await response.json()
        setGlobalData(data)
    }
    getData()
   }, [])

console.log(globalData.confirmed.value)

But It gives me this error

    TypeError: Cannot read property 'value' of undefined
Cards
D:/Bootcamp Projects/Covid-19 Tracker App/src/Components/Cards/Cards.js:18
  15 |        getData()
  16 |    }, [])
  17 | 
> 18 |    console.log(globalData.confirmed.value)
     | ^  19 | 
  20 |  return (
  21 |    <div className="Cards">

I've tried so many methods but didn't got any solution... Looking forward to a solution...

Amir Shahzad
  • 73
  • 1
  • 6
  • 3
    I suppose `globalData` is an empty object before the data is fetched, you will have to handle that – Andrew Li Feb 09 '21 at 19:20
  • Yes you are right. I've updated my code in this question. Can you please explain me a little bit how can I solve my problem... Thanks – Amir Shahzad Feb 09 '21 at 19:35
  • Does this answer your question? [JavaScript "cannot read property "bar" of undefined](https://stackoverflow.com/questions/8004617/javascript-cannot-read-property-bar-of-undefined) – Emile Bergeron Feb 09 '21 at 19:41
  • 2
    @AmirShahzad The problem is that `globalData.confirmed` is undefined (since `globalData` is empty) before you finish fetching (and call `setGlobalData`). You'll have to check if `globalData.confirmed` isn't undefined before you access it. Or better yet, use a `loading` state variable, and set loading to false once you're done fetching. Then just check if it's loaded before you access any data. – Andrew Li Feb 09 '21 at 19:43

1 Answers1

1

set it to null originally and wait for the data to exist

EDIT: to explain a bit better, the global data state is null initially. because this is a falsy value, we can use the && operators to wait for the data to exist and become a truthy value

import React, { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [globalData, setGlobalData] = useState(null);

  useEffect(() => {
    async function getData() {
      const response = await fetch("https://covid19.mathdro.id/api");
      const data = await response.json();
      setGlobalData(data);
    }
    getData();
  }, []);

  console.log(globalData && globalData.confirmed.value);
  return <div className="App"></div>;
}
Rob Terrell
  • 2,398
  • 1
  • 14
  • 36
  • Thanks for your answer it helped me a lot, but instead of setting it to "null" I've set the state to "Number", that cleared all my errors from the console. Thanks again for your help.. – Amir Shahzad Feb 09 '21 at 20:35
  • not sure how the solution above causes any errors in the console, but glad you found a solution. also not sure what you mean by you set the state to number – Rob Terrell Feb 09 '21 at 20:38
  • const [globalData, setGlobalData] = useState(Number); – Amir Shahzad Feb 10 '21 at 09:22