Recently, I encountered an issue while trying to retrieve a random user from the randomuser API using code in my Vue frontend.
// Here is the structure of the API response
{ info: { // details omitted }, results: [ {//random user data} ] }
// This snippet of code works perfectly fine
async get_random_user() {
const url = "https://randomuser.me/api/";
const res = await fetch(url);
const json_data = await res.json();
const result = json_data.results[0];
return result;
}
// However, this alternative approach throws an error - Uncaught (in promise) TypeError: Cannot read property '0' of undefined
async get_random_user() {
const url = "https://randomuser.me/api/";
const res = await fetch(url);
const result = await res.json().results[0];
return result;
}
I'm struggling to understand why the second function isn't working as expected. Any insights or solutions would be greatly appreciated. Thanks!