Last active
April 19, 2022 13:56
-
-
Save tyte/9a0ae3865fb57e391eaae1f9a5c847b1 to your computer and use it in GitHub Desktop.
JS fetch api example with random quotes
This file contains hidden or 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> | |
<head> | |
<meta charset="utf-8"> | |
<title>Random Ron</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<style type="text/css"> | |
body { | |
margin: 0 auto; | |
max-width: 40em; | |
width: 88%; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Random Ron</h1> | |
<blockquote id="quote" aria-live="polite"></blockquote> | |
<p> | |
<button id="get-quote">More Ron</button> | |
</p> | |
<script> | |
// Your code goes here... | |
let button = document.querySelector('#get-quote'); | |
let quote = document.querySelector('#quote'); | |
let api = 'https://ron-swanson-quotes.herokuapp.com/v2/quotes'; | |
button.addEventListener('click', function() { | |
displayQuote(); | |
}); | |
function displayQuote() { | |
// 1. Fetch - if response is ok, then return json, otherwise throw error | |
// 2. Then chain .then to do stuff with data | |
// 3. Then chain .catch for errors | |
fetch(api).then(function (response) { | |
if (response.ok) { | |
return response.json(); | |
} | |
throw response.status; | |
}).then(function (data) { | |
quote.textContent = data; | |
}).catch(function (error) { | |
console.warn(error); | |
}); | |
} | |
displayQuote(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment