Skip to content

Instantly share code, notes, and snippets.

@bryancodesjs
Created January 22, 2022 03:26
Show Gist options
  • Save bryancodesjs/5cfe456a3ff142c5e9db2df007a52960 to your computer and use it in GitHub Desktop.
Save bryancodesjs/5cfe456a3ff142c5e9db2df007a52960 to your computer and use it in GitHub Desktop.
Fetch data from an API and appending the results to an unordered list
//this is a mock API I made for the occasion
const submitUrl = 'https://retoolapi.dev/QqocMc/data';
//this selects the unordered list with the id 'list' on the html template
//you should have that set up beforehand
const htmlListNode = document.getElementById('list');
//Use the fetch method and pass it the url of the API
fetch(submitUrl)
.then(res => res.json()) //parse the response and then...
.then(data => {
let length = data.length; //save the length of the array to use it as a reference in the loop
for(let i = 0; i < length; i++) {
//console.log for debugging
console.log(data[i]);
let userid = data[i].id; //save the user in a variable
let username = data[i].user; //save the username
let serviceLocation = data[i].number; //save the service location
let listElem = document.createElement("li"); //create a list item in memory
let idNode = document.createElement("h2"); //create an h2 heading in memory
idNode.innerHTML = username + '<strong> (' + userid + ')</strong>'; //assign the the user id and user name to the heading
let locationNode = document.createElement("p"); //create a 'p' virtual element
locationNode.innerText = serviceLocation; //assing the service location to the 'p' element
listElem.appendChild(idNode); //append each h2 heading to the virtual its list item
listElem.appendChild(locationNode); //append each p element to its list item
htmlListNode.appendChild(listElem); //append each list item to the unordered list of id 'list' in the DOM
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment