Skip to content

Instantly share code, notes, and snippets.

@tyte
Last active April 26, 2022 17:50
Show Gist options
  • Save tyte/4961e2bf5b19262d6cca99bea687928e to your computer and use it in GitHub Desktop.
Save tyte/4961e2bf5b19262d6cca99bea687928e to your computer and use it in GitHub Desktop.
JS inject content from API
<!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>
// Your code goes here...
let app = document.querySelector('#app');
let api = 'https://vanillajsacademy.com/api/dragons.json';
// create an empty array that will store quotes
// Async ALWAYS returns a promise, even if you are not using asynchronious code.
async function displayArticles() {
try {
let response = await fetch(api);
if (!response.ok) {
throw response.status;
}
let data = await response.json();
if (!data) throw 'No data';
let articles = data['articles'];
let appContent = `
${articles.map(function (article){
return `<section style="margin-bottom: 2em;">
<h2 id="${article['url']}">${article['title']}</h2>
<span>${article['pubdate']}</span><br>
<p>${article['article']}</p>
<span style="font-style:italic;">by ${article['author']}</span>
</section>`;
}).join('')}
`;
app.innerHTML = appContent;
} catch (error) {
app.innerHTML = `<p style="text-align:center;">Just a boring arror here!</p>`;
}
}
displayArticles();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment