Created
June 2, 2021 01:09
-
-
Save Sazzo/ac38ee1e4546fbf2b9d7fa74ed8e15ae to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Random User Generator</title> | |
</head> | |
<body> | |
<center> | |
<h1>Random User Generator</h1> | |
<button id="gerar">Gerar</button> | |
<div id="results"></div> | |
</center> | |
<script> | |
const gerarButton = document.getElementById("gerar"); | |
const resultsDiv = document.getElementById("results"); | |
gerarButton.addEventListener("click", () => { | |
fetch("https://randomuser.me/api") | |
.then((response) => { | |
/* | |
Geralmente eu não iria usar o .then, e sim deixar o callback do evento de click | |
assíncrono (async) e usar um await no response.json e no fetch, já que são *promises* | |
porém, por efeito de simplicidade e eu imagino que tu nem saiba o que é promise ou async ou await | |
vou deixar sem. | |
*/ | |
const responseJSON = response.json().then((json) => { | |
// Limpar a DIV para que não fique colocando um usuário em cima do outro antigo. | |
resultsDiv.innerHTML = ""; | |
const user = json.results[0]; | |
const username = document.createElement("p"); | |
username.innerText = `Name: ${user.name.title} ${user.name.first} ${user.name.last}`; | |
const email = document.createElement("p"); | |
email.innerText = `Email: ${user.email}`; | |
resultsDiv.appendChild(username); | |
resultsDiv.appendChild(email); | |
}); | |
}) | |
.catch((error) => { | |
// Nota: \n = pular linha | |
resultsDiv.innerText = `Um erro aconteceu!\n${error}`; | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment