28. API Cache - Fallback

Loading...

HTML

1
2
3
<div id="app">
Loading...
</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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* In today’s project, we’re going to modify our API cache script
to fallback to the cache if the API call fails—even if data has expired.
Showing something, even if it’s a bit out of date, is better than showing nothing at all.*/

const appOutput = document.querySelector('#app');
let storageID;
var numberOfArticles = 2;
const sanitizeHTML = function (str) {
return str.replace(/[^\w. ]/gi, function (c) {
return '&#' + c.charCodeAt(0) + ';';
})
};
const isDataValid = function (saved, expirationDate) {
if (!saved || !saved.data || !saved.timestamp) return false;
const difference = new Date().getTime() - saved.timestamp;
return difference < expirationDate;
}
const saveData = function (data) {
const cache = {
data: data,
timestamp: new Date().getTime()
}
localStorage.setItem(storageID, JSON.stringify(cache));
}
const getData = function () {
const saved = JSON.parse(localStorage.getItem(storageID));
if (!saved) return;
if (isDataValid(saved, 1000 * 10)) {
return saved.data;
}
}
const render = function (articles) {
appOutput.innerHTML = '<h3 class="category">Pirate articles:</h3>' + articles.map(function (article) {
return (`
<div class="container">
<ul class="title">
<li> <strong>Title:</strong> ${sanitizeHTML(article.title)}</li>
<li> <strong>Author:</strong> ${sanitizeHTML(article.author)}</li>
<li> <strong>Publication date:</strong> ${sanitizeHTML(article.pubdate)}</li>
</ul>
<div class="article"><p>${sanitizeHTML(article.article)}</p></div>
</div>
<hr>
<br>
`);
}).join('');
}
const getFirstFewArticles = function (articles) {
return articles.slice(0, numberOfArticles);
}
const getNews = function () {
// Check for valid cached data,
// If exist, use it
const saved = getData();
if (saved) {
render(saved);
console.log("Loaded from cache");
return;
}
fetch('https://vanillajsacademy.com/api/pirates.json').then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
}).then(function (data) {
const articles = getFirstFewArticles(data.articles);
saveData(articles);
render(articles);
console.log("Fetched from API");
}).catch(function (error) {
console.log("something went wrong", error);
appOutput.textContent = "Something went wrong...";
})
}
getNews();