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:
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))
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();
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 ...
});