Last active
April 20, 2022 18:29
-
-
Save tyte/33147d200e534f3ed39b87db3c2e0fae to your computer and use it in GitHub Desktop.
JS fetch unique quotes from api
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> | |
<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"> | |
<em>Quotes are on their way...</em> | |
</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'; | |
// create an empty array that will store quotes | |
let quotes = []; | |
button.addEventListener('click', 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) { | |
if (quotes.length > 50) { | |
quotes = quotes.shift(quotes.length - 50); | |
}; | |
if (quotes.includes(data[0])) { | |
// console.log('SAME COPY!'); | |
// console.log(data[0]); | |
displayQuote(); | |
} else { | |
quote.textContent = data[0]; | |
quotes.push(data[0]); | |
// console.log(quotes); | |
} | |
}).catch(function (error) { | |
quote.textContent = 'Error message, a very beautiful one.' | |
}); | |
} | |
displayQuote(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment