Skip to content

Instantly share code, notes, and snippets.

@angusgrant
Created November 2, 2022 00:14
Show Gist options
  • Save angusgrant/43792106a1dc6a99390003f99300f1ce to your computer and use it in GitHub Desktop.
Save angusgrant/43792106a1dc6a99390003f99300f1ce to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dragon Trainer Monthly</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>Dragon Trainer Monthly</h1>
<div id="app"></div>
<script>
const appendPoint = document.querySelector('#app');
const jsonEndpoint = 'https://vanillajsacademy.com/api/dragons.json';
let htmlToAppend = '';
//wrap in iife to fire function on page load.
(async function getDragons () {
try {
const response = await fetch(jsonEndpoint);
if (!response.ok){
throw response.status;
}
const data = await response.json();
//check if some data exists
if (data.articles[0].title){
//append to template literal string use MAP function to augment the array of Articles
htmlToAppend = `
${data.articles.map(function(art) {
return `<article style="margin-bottom:10px">
<h2>${art.title}</h2>
<p><strong>By:</strong> ${art.author}<p>
<p>${art.article}</p>
<time style="display:block;text-align:right;">${art.pubdate}</time>
</article>`
}).join('')}
`;
//end template literal string
//append to the DOM app element
appendPoint.innerHTML = htmlToAppend;
}
} catch (error) {
appendPoint.innerHTML = `<h2>Something went wrong!</h2>
<p>This is the error returned from the API:</p>
<p>${error}</p>`;
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment