I'm in the process of learning how to make fetch api calls and return an array with a list of certain usernames. In the below code that I've written, the array that I was looking for seems to have been generated fine. However, when I try using .forEach() method on the array, it just does not seem to work. If I change the array contents to simple numbers like 1,2,3 etc, the .forEach() method seems to work as expected. Please let me know what am I missing out here? Thanks!
function getUsers() {
let returnArray = [];
fetch("https://api.github.com/users")
.then((data) => data.json())
.then((data) => {
data.forEach((item) => {
returnArray.push(item.login);
});
});
return returnArray;
}
function createListItem(text) {
let li = document.createElement("li");
li.textConent = text;
return li;
}
function addUsersToDOM() {
let body = document.getElementById("my-body");
namesArray = getUsers();
console.log(namesArray); //Getting an array with the text elements
namesArray.forEach((item) => {
console.log(item); // Console log of individual text elements not working
});
}
addUsersToDOM();
If I change the array contents to simple numbers like 1,2,3 etc, the .forEach() method seems to work as expected.