JSFiddle - React, Tailwind, and code Playground
by Eric Pias
HTML
<body>
<h1>Testing code of offline cache.</h1>
<hr>
<h2>Results:</h2>
<div id="results">
</div>
</body>
JavaScript
var OfflineCache = {
get: function(key) {
var ocData = localStorage.getItem("offlineCache");
if (ocData) {
// turn JSON into an object
ocData = JSON.parse(ocData);
if (ocData) {
for (var i=0; i<ocData.length;i++) {
if (ocData[i].id == key) {
return ocData[i];
}
}
}
}
return null;
},
contains: function(key) {
var ocData = localStorage.getItem("offlineCache");
if (ocData) {
// turn JSON into an object
ocData = JSON.parse(ocData);
if (ocData) {
for (var i=0; i<ocData.length;i++) {
if (ocData[i].id == key) {
return true;
}
}
}
}
return false;
},
put: function(key, item) {
try {
var ocData = localStorage.getItem("offlineCache");
if (!ocData) {
// Note: local storage only supports stringified objects in web storage
ocData = [];
}
else {
// turn JSON into an object
ocData = JSON.parse(ocData);
}
if (ocData) {
if (!this.contains(key))
ocData.push(item);
else {
// need to update the item in the array
for (var i=0; i<ocData.length;i++) {
if (ocData[i].id == key) {
ocData.splice(i, 1, item);
}
}
}
}
localStorage.setItem("offlineCache", JSON.stringify(ocData));
return true;
} catch (e) {
return false;
}
},
remove: function(key) {
var ocData = localStorage.getItem("offlineCache");
if (ocData) {
// turn JSON into an object
ocData = JSON.parse(ocData);
if (ocData) {
for (var i=0; i<ocData.length;i++) {
if (ocData[i].id == key) {
ocData.splice(i, 1);
break;
}
}
// now put the stringified object back in cache
localStorage.setItem("offlineCache", JSON.stringify(ocData));
}
}
},
removeAll: function() {
localStorage.removeItem("offlineCache");
},
toJSON: function() {
return localStorage.getItem("offlineCache") || "";
},
hasItems: function() {
var ocData =...