Skip to content

Instantly share code, notes, and snippets.

@sergiodxa
Last active June 11, 2019 16:04
Show Gist options
  • Save sergiodxa/520e3683e80848de8313d85444411ab6 to your computer and use it in GitHub Desktop.
Save sergiodxa/520e3683e80848de8313d85444411ab6 to your computer and use it in GitHub Desktop.
Fetch data from an API and show it in the DOM. Save the data on the Storage and use it when the user reload to immediately update the DOM while fetching new data from the API.
const URL = "https://jsonplaceholder.typicode.com/posts?_page=2";
async function getData(staleData = {}) {
const response = await fetch(URL);
const data = await response.json();
return data.reduce((posts, post) => {
return {
...posts,
[post.id]: posts.hasOwnProperty(post.id)
? { ...posts[post.id], ...post }
: post
};
}, staleData);
}
function getStaleData() {
const data = localStorage.getItem("cache");
if (data === null) return {};
return JSON.parse(data);
}
function updateCache(data) {
localStorage.setItem("cache", JSON.stringify(data));
}
function render(data, $app) {
Array.from($app.children).forEach($child => $app.removeChild($child));
Object.values(data)
.map(datum => {
const $article = document.createElement("article");
const $h2 = document.createElement("h2");
const $p = document.createElement("p");
$article.appendChild($h2);
$article.appendChild($p);
$h2.innerText = datum.title;
$p.innerText = datum.body;
return $article;
})
.reduce(($app, $article) => {
$app.appendChild($article);
return $app;
}, $app);
}
async function main($app) {
console.info("Starting application");
const staleData = getStaleData();
if (Object.keys(staleData).length > 0) {
console.info("Rendering stale data");
render(staleData, $app);
}
console.info("Fetching new data");
const data = await getData(staleData);
console.info("Updating cache with new data");
updateCache(data);
console.info("Rendering new data");
render(data, $app);
}
main(document.getElementById("app")).catch(error => console.error(error));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment