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...
globalDatais an empty object before the data is fetched, you will have to handle thatglobalData.confirmedis undefined (sinceglobalDatais empty) before you finish fetching (and callsetGlobalData). You'll have to check ifglobalData.confirmedisn't undefined before you access it. Or better yet, use aloadingstate variable, and set loading to false once you're done fetching. Then just check if it's loaded before you access any data.