Created
April 25, 2021 00:36
-
-
Save passandscore/6eda0d2db3ddc3a810a9df13a4478eba to your computer and use it in GitHub Desktop.
Fetch API method( )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//FETCH API - DOM template | |
//Language: JavaScript | |
function loadRepos() { | |
const username = document.getElementById('username').value; //user input value | |
const repos = document.getElementById('repos'); //DOM element to display data | |
repos.innerHTML = ''; | |
//construct the URL | |
const url = `https://api.github.com/users/${username}/repos` | |
fetch(url).then((resp) => { | |
//Handle the server status | |
if (resp.ok) { | |
return resp.json(); | |
} | |
throw new Error(`${resp.status} - ${resp.status.Text}`); | |
//Handle the incoming data | |
}).then((data) => { | |
console.log(data) | |
data.forEach(repo => { | |
let li = document.createElement('li'); | |
let a = document.createElement('a'); | |
a.href = repo.html_url; | |
a.textContent = repo.full_name; | |
li.appendChild(a); | |
repos.appendChild(li); | |
}); | |
//Handle the errors | |
}).catch((err) => { | |
let li = document.createElement('li'); | |
li.textContent = `${err}`; | |
repos.appendChild(li); | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment