Skip to content

Instantly share code, notes, and snippets.

@tyte
Last active April 19, 2022 13:56
Show Gist options
  • Save tyte/9a0ae3865fb57e391eaae1f9a5c847b1 to your computer and use it in GitHub Desktop.
Save tyte/9a0ae3865fb57e391eaae1f9a5c847b1 to your computer and use it in GitHub Desktop.
JS fetch api example with random quotes
<!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