10. Latest 3 top stories on few categories

HTML

1
2
3
<div id="app">
<span id="placeholder"></span>
</div>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* Get articles from three to five categories, then render the API data
into markup and inject it into the #app element. Instead of rendering all of the articles,
use the first five from each category. Add a heading before each section so that you know
what category the articles are from. */

const appOutput = document.querySelector('#app');
const apiKey = 'T6l8P8ICK6XZr1u3OeA0qoGUFrEcSM5R';
const sections = ['Technology', 'Science', 'Magazine'];
const articleNum = 3;

const render = function (articles, section) {
appOutput.innerHTML += '<h3 class="category">' + section + ':' + '</h3>' + articles.map(function (article) {
return (`
<div class="container">
<ul class="title">
<li>${article.title}</li>
<a class="link" href="${article.url}" target="_blank">Read more</a>
</ul>
</div>
<br>
`);
}).join('')
};

const getLastNStories = function (articles) {
return articles.slice(0, articleNum)
}

const getStories = function (section) {
fetch(`https://api.nytimes.com/svc/topstories/v2/${section}.json?api-key=${apiKey}`).then(
function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
};
}).then(function (data) {
const lastNStories = getLastNStories(data.results);
render(lastNStories, section);
}).catch(response => {
console.log("something went wrong", response);
appOutput.textContent = "Something went wrong...";
});
};

sections.forEach(function (section) {
getStories(section);
});