I am working on grasping the concept of functional programming. My understanding so far is that it involves encapsulating everything into functions and passing them around. For instance, in my current example, I am attempting to fetch data from a RESTApi and display it in the DOM:
const storyElement = function (): HTMLElement {
const div = document.createElement('div');
div.className = 'stories';
return div;
};
const spinnerElement = function (): HTMLElement {
const div = document.createElement('div');
div.className = 'spinner';
div.innerHTML = `<svg class="spinner" viewBox="0 0 100 100" width="20" height="20">
<circle cx="50" cy="50" r="42" transform="rotate(-90,50,50)" />
</svg>`;
return div;
};
In this scenario, there are two divs - one for displaying Stories and another for a loading icon. Once the content is rendered, the loading icon should disappear.
function getAllStories(callback): void {
makeRequest(baseUrl(), (res) => spawn(res, callback));
}
function spawn(content, callback): void {
content = JSON.parse(content);
if (content instanceof Array === false) {
content = [content];
}
content.forEach(elm =>
storyElement().innerHTML += `<h1>${elm.title}</h1>
<div class="story-info">
<i>ID: Post-${elm.id}</i>
</div>
<p>${elm.body}.</p>`
);
console.log(content);
callback();
}
function displayFinished(): void {
spinnerElement().style.display = 'none';
document.body.innerHTML += '<div>All done!</div>';
}
However, upon executing getAllStories
, the result is logged in the console but the content does not appear in the DOM:
document.body.appendChild(storyElement());
document.body.appendChild(spinnerElement());
getAllStories(displayFinished);
Any insights on why this might be happening?