0

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

jibaro
  • 103
  • 1
  • 12

3 Answers3

1

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;
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
  • Thanks! This indeed shows the property I wanted to log. But how could I destructure this so I can access the value a little easier? ideally I want to do something like ({ data: {confirmed} }) in the params – jibaro Jun 13 '20 at 07:06
1

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?

hangindev.com
  • 4,573
  • 12
  • 28
1

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();
  }, []);
ABGR
  • 4,631
  • 4
  • 27
  • 49