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...

4
  • 3
    I suppose globalData is an empty object before the data is fetched, you will have to handle that Commented Feb 9, 2021 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 Commented Feb 9, 2021 at 19:35
  • Does this answer your question? JavaScript "cannot read property "bar" of undefined Commented Feb 9, 2021 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. Commented Feb 9, 2021 at 19:43

1 Answer 1

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>;
}
Sign up to request clarification or add additional context in comments.

3 Comments

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..
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
const [globalData, setGlobalData] = useState(Number);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.