miguelslp - Vanilla JS

Sanitizing the NYT API Data

Loading latest stories...
<div id="app">
<span id="placeholder">Loading latest stories...</span>
</div>

<script async>
// Variables
let elem = document.querySelector("#app");
let apiKey = "V4DAxXaiDzvGkumnpxfO4LpmCd7dM9om";
let sections = ["automobiles", "books", "health", "travel"];
let numberOfArticles = 2;

// Methods
// ---Get the arrays and call updateDOM
function callNYT(section) {
fetch(
`https://api.nytimes.com/svc/topstories/v2/${section}.json?api-key=${apiKey}`
)
.then((response) => response.ok ? response.json() : Promise.reject(response))
.then((array) => updateDOM(array))
.catch((error) => errorState(error, section));
}

// ---Helper function to insert the newest 5 as list items in the DOM
function updateDOM(array) {
let latestArticles = array.results.slice(0, numberOfArticles);
let stories = latestArticles
.map(function (story) {
return `<article><a href="${sanitizeHTML(story.short_url)}">${sanitizeHTML(story.title)}</a></article>`;
})
.join("");
let placeholder = document.querySelector("#placeholder");
if (placeholder) placeholder.remove();
elem.innerHTML += `<h2>${sanitizeHTML(array.section)}</h2>${stories}`;
}

// ---Sanitizing function
function sanitizeHTML(str) {
return str.replace(/[^\w. ]/gi, function (c) {
return "&#" + c.charCodeAt(0) + ";";
});
}

// ---Error message UI
function errorState(error, section) {
console.warn("Oh no something went wrong", error);
let placeholder = document.querySelector("#placeholder");
if (placeholder) placeholder.remove();
let errorState = document.querySelector("#errorState");
if (!errorState) {
errorState = document.createElement("p");
errorState.setAttribute("id", "errorState");
errorState.textContent =
"Sorry, something went wrong gathering stories on";
app.after(errorState);
}
errorState.innerHTML += `
<code> ${section}</code>
`
;
}

// Inits
sections.forEach((section) => callNYT(section));
</script>