Home > Enterprise >  Why object displayed in console.log, but I can't access a property of it? [closed]
Why object displayed in console.log, but I can't access a property of it? [closed]

Time:09-25

Console log object

I was working on ReactJS and fetching data from an API. At point point, I did console.log(regional[1]) which returned me this. Now I'm unable to do console.log(regional[1].deaths) which gives error :

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'deaths')

I think this is due to

ConfirmedCasesForiegn: 0 

which is returning null value. How to delete this from my object

The code of fetching and console:

    const updateData = async()=>{
    const url = 'https://api.rootnet.in/covid19-in/stats/latest';
    let cdata = await fetch(url);
    let parsedData = await cdata.json();
    setRegional(parsedData.data.regional);
    setSummary(parsedData.data.summary);
    // console.log(regional[1]['deaths']);
    // console.log(JSON.stringify(regional[1],null,2))
    console.log(regional[0]?.deaths)

CodePudding user response:

This is because initially at some point regional [1] is undefined (before getting data from api) and reactjs is unable to get property deaths of undefined. To solve this issue either check undefined using ternary operator or you can simply use ES syntax and get data as regional [1]?. deaths This will prevent error if regional[1] is undefined

Edit: console.log(regional[1]?.deaths)

CodePudding user response:

This is nothing to do with ConfirmedCasesForeign: 0

The value of that property cannot interfere with the property you are accessing.

When you say ConfirmedCasesForeign is returning a "null object", actually it isn't. It is returning 0. null is a different object.

Very likely this is a timing problem

I suspect you are reading data from the internet, yes? If so, I suspect you are not waiting for the result before you access ".deaths"

The reason the console.log shows everything, is that console.log shows you the most recent version of the object, not the one that was present at the time of console.log execution.

Debugging

To test this, change the console log to:

console.log(JSON.stringify(regional[1],null,2))

If this is "undefined", then it is indeed a timing problem. Check your method of accessing the web API. Do you have a way of running your function only once the result is back? For example, it could be by promises or by callbacks.

That would solve your problem.

If you show us your API call we may be able to advise. Or check the documentation to see if there is a callback or promise method you can use.

  • Related