Home > Software engineering >  Uncaught TypeError: Cannot read properties of undefined (reading 'dailyconfirmed')
Uncaught TypeError: Cannot read properties of undefined (reading 'dailyconfirmed')

Time:04-15

what's problem with my code i am getting error while accesing mydata.dailyconfirmed after page reloading?

 const[state,setState]=useState({});
async function getApiIndia1(){
   const temp=await fetch('https://data.covid19india.org/data.json')
   const mydata=await temp.json();
   setState(mydata)
}
useEffect(() => {
    getApiIndia1();
}, [])

CodePudding user response:

If you check the api response properly you will get to know what you are missing. The api response is and object and tha object doesn’t have any key named dailyconfirmed.


{
    "cases_time_series": [
        {
            "dailyconfirmed": "1",
            "dailydeceased": "0",
            "dailyrecovered": "0",
            "date": "30 January 2020",
            "dateymd": "2020-01-30",
            "totalconfirmed": "1",
            "totaldeceased": "0",
            "totalrecovered": "0"
        },
        …
}

Try mapping mydata.cases_time_series which is an array of objects and those objects having the key which you trying to access.

CodePudding user response:

Update the setState

setState(mydata.cases_time_series)

and when you wish to find dailyconfirmed, loop over your state which is basically an array of object.

state.map((dailyconf)=>{
if(dailyconf?.dailyconfirmed) console.log(dailyconf?.dailyconfirmed)
})

CodePudding user response:

You cannot access mydata outside of getApiIndia1 (which I assume you are trying to do). It is only defined in that block, which is the reason why you're using state (essentially to save the required data globally). mydata can't be found and that's why it's throwing an error. What you should do instead is access state, which is where you're storing that data.

But that will still throw an undefined. That's because of the issue that previous answers have already highlighted. You need to access state.cases_time_series.dailyconfirmed. That should give you the data you want.

It's always a good idea to check API responses carefully. ;)

  • Related