If I try to console.log the array 'profiles' I only get results when in the fetch code block, outside fetch code block the array is empty. Anyone has an idea how this comes?
I removed some variables to reduce the code but the problem only takes place outside of the fetch code block, in other words, outside of the function getTinderProfiles()
.
While I'm clearly storing the data of the person object in the array 'profiles' I can not think of a problem to log the data of that array.
let url = 'https://randomuser.me/api/?results=11';
let profiles = [];
let Person = new Object();
function getTinderProfiles() {
fetch(url)
.then(function (response) {
return response.json();
})
.then(function (tinderUsers) {
// Get 10 users and put data in object
let randomUser = tinderUsers.results;
for (let i = 0; i < randomUser.length; i++) {
Person = {
picture: randomUser[i].picture.large,
name: randomUser[i].name.first + ' ' + randomUser[i].name.last,
age: 'Age: ' + randomUser[i].dob.age,
location: randomUser[i].location.city + ' ' + randomUser[i].location.postcode + '<br>' + randomUser[i].location.street,
}
// console.log(JSON.stringify(Person));
// Add fetched persons to profiles array
function pushToProfiles() {
profiles.push(Person);
console.log(profiles);
}
pushToProfiles();
console.log(profiles[0]); // RESULTS !!!
});
}
getTinderProfiles();
console.log(profiles); NO RESULTS !!!