1

below code is showing 'undefined' in console. while the api has data inside it.

const getFakePerson = async () => {
  let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
  let { results } = res.json();
  console.log(results);
}
getFakePerson();

Result:

Result

AlleXyS
  • 2,476
  • 2
  • 17
  • 37

3 Answers3

1

res.json() returns a promise. You need to await it.

const getFakePerson = async () => {
  let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
  let results = await res.json();
  console.log(results);
}
getFakePerson();

Alternately, you can use

res.json().then(data => console.log(data))
0

From discussion and testing the code I knew that we have to add await keyword before res.json().

const getFakePerson = async () => {
    let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
    let { results } = await res.json();
    console.log(results);
}
getFakePerson();
Sparrow
  • 280
  • 1
  • 12
0

The elephant in the room as pointed out already was that on line 3, there was a missing await for the res.json() call.

On top of that, I would recommend separating concerns here. Let the getRandomPerson return the person and then console.log later on in the process. Such as this:

const getFakePerson = async () => {
    let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
    let { results: person } = await res.json();

    return person
}

getFakePerson().then(generatedPerson => {
   console.log(generatedPerson)
   // ... do more here ...
});
marpme
  • 2,363
  • 1
  • 15
  • 24
  • 1
    You don't even need to await the parsed JSON. You can just do `return res.json();` because the returned data is still a promise. – Andy Oct 16 '21 at 06:31
  • Semantically that would mean something different then as we are extracting the `results: person` from the JSON object. – marpme Oct 16 '21 at 11:25