Last active
April 29, 2022 22:08
-
-
Save tyte/a364b0bc0eaaf1013efb8f1c4f50a69f 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> | |
<head> | |
<meta charset="utf-8"> | |
<title>Dragon Trainer Monthly - Author Data</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%; | |
} | |
article { | |
margin-bottom: 3em; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Dragon Trainer Monthly - Author Data</h1> | |
<div id="app"></div> | |
<script> | |
// Get the app element | |
let app = document.querySelector('#app'); | |
/** | |
* Render an error message if fetch fails | |
*/ | |
function renderFail () { | |
app.innerHTML = '<p>The dragons burned all the copies. Unable to get new articles at this time. Sorry!</p>'; | |
} | |
/** | |
* Render articles into the DOM | |
* @param {Array} articles The articles to render | |
*/ | |
function render (articles, authors) { | |
// If there are no articles to show | |
if (!articles || articles.length < 1) { | |
renderFail(); | |
return; | |
} | |
// Create a new array of markup strings with array.map(), then | |
// Combine them into one string with array.join(), then | |
// Insert them into the DOM with innerHTML | |
app.innerHTML = articles.map(function (article) { | |
let currentAuthor = authors.find(function (author) { | |
return author.author === article.author; | |
}); | |
return ` | |
<article> | |
<h2><a href="${article.url}">${article.title}</a></h2> | |
<p><em>By ${article.author}</em></p> | |
<p>${article.article}</p> | |
<p>${currentAuthor.author} | |
</article>`; | |
}).join(''); | |
} | |
// Get articles and authors | |
Promise.all([ | |
fetch('https://vanillajsacademy.com/api/dragons.json'), | |
fetch('https://vanillajsacademy.com/api/dragons-authors.json') | |
]).then(function (responses) { | |
return Promise.all(responses.map(function (response) { | |
return response.json(); | |
})); | |
}).then(function (data) { | |
// Render them into the DOM | |
render(data[0].articles, data[1].authors); | |
}).catch(function (error) { | |
console.log(error); | |
renderFail(); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment