0

I am trying to grab the concept of destructing properly. I understand that it is a way of assigning values to a variable from an object or array. I have a data fetched from an API this way

const getAUserProfile = () => {
  const api = "https://randomuser.me/api/";

  const data = fetch(api).then(response => {
    return response.json();
  });

  console.log(data);
  displayUserPhotoAndName(data);
};

the console.log result shows this enter image description here

In the displayUserPhotoAndName function, I am attempting to destructure the data like this

const displayUserPhotoAndName = data => {
    const {results} = data;
    console.log(results);
};

But console.log(results) returns undefined. Apparently I seem not to be destructuring the data properly or my fetch method is not correct, these are my thoughts. Please what would be the right way to destructure data in this case?

Mena
  • 1,873
  • 6
  • 37
  • 77
  • 1
    You need `fetch(api).then(r => r.json()).then(data => displayUserPhotoAndName(data));` –  Apr 10 '19 at 09:07
  • 1
    It's a promise. At the moment of `displayUserPhotoAndName` data is not resolved yet. You will need to unwrap data from promise as well. – dubadub Apr 10 '19 at 09:07
  • @ChrisG great! apparently my fetch method wasn't complete yet – Mena Apr 10 '19 at 09:11
  • @dubadub your explanation made it very clear what the issue was, now I can see the expected message. – Mena Apr 10 '19 at 09:12
  • Yes, fetch() is asynchronous. Btw I just noticed you can do `fetch(api).then(r => r.json()).then(displayUserPhotoAndName);` –  Apr 10 '19 at 09:13

0 Answers0