简体   繁体   中英

Can't access api object properties - react Hooks

I've console.log'd the data being returned from my API and I get:

​
fetchedData: {…}
​​
confirmed: Object { value: 7650696, detail: "https://covid19.mathdro.id/api/confirmed" }
​​
deaths: Object { value: 425869, detail: "https://covid19.mathdro.id/api/deaths" }
​​
lastUpdate: "2020-06-13T04:33:11.000Z"
​​
recovered: Object { value: 3630249, detail: "https://covid19.mathdro.id/api/recovered" }
​​
<prototype>: Object { … }
​
<prototype>: Object { … }

Then, when I console.log(data.confirmed) I receive undefined, even though it's listed right there. I'm using hooks in my app, though I'm not sure that has anything to do with it because I'm able to console the data just fine. The problem is when I try to access the properties in data.

https://codesandbox.io/s/wizardly-banzai-2n2xq?file=/src/App.js

It should be

console.log(data.fetchedData && data.fetchedData.confirmed)  

instead

console.log(data.confirmed) 

Updated codesandbox

EDIT:

Using destructuring assignment , it should be like this.

let { fetchedData: {
  confirmed
} = {
    confirmed: 'defaullt value'
  }
} = data;

setState is asynchronous that's why data is still an empty object when console.log is executed. Here is a quote from the React docs :

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

The reason you can see the whole object when you console.log(data) is that console.log may not evaluate the object values until you click the expand arrow.

console.log in different environments (browsers) may have different implementations.

If you want to see how data looks like at the moment after setData({fetchedData});is executed, you may log it this way:

console.log(JSON.parse(JSON.stringify(data)));

For more about the "mystery" of console.log , please check console.log() async or sync?

You really don't wanna destructure there. But if you want, you can do something like this: https://codesandbox.io/s/peaceful-blackburn-ywdzu?file=/src/App.js:177-667

 const [data, setData] = useState({});
  const [recovered, setRecovered] = useState({});
  const [confirmed, setConfirmed] = useState({});
  const [deaths, setdeaths] = useState({});

  useEffect(() => {
    async function fetchData() {
      const fetchedData = await virusData();
      const { confirmed, recovered, deaths } = fetchedData;
      setData(fetchedData);
      setRecovered(confirmed);
      setConfirmed(recovered);
      setdeaths(deaths);
    }
    fetchData();
  }, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM