TIL LocalForage, a small js library for caching
POSTED ON:
TAGS: javascript webdev cache api mdn library
You might do a really expensive 2meg API call to pull some data.
What if the API was down? Do you want your web app to fail for existing users?
You can use localStorage/sessionStorage, and also IndexedDB.
But why not both?
LocalForage, a tiny JS library, can do that for us.
It's the standard (CRUD) operations:
- Create a new cache
- Add (update) items to a cache
- Retrieve items from a cache
- Delete items from a cache
// Feel free to change the drivers order :)
localforage.setDriver([
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
]).then(function() {
var key = 'STORE_KEY';
// var value = 'What we save offline';
var value = 'asdf';
value[0] = 65
// var value = undefined;
var UNKNOWN_KEY = 'unknown_key';
localforage.setItem(key, value, function() {
console.log('Using:' + localforage.driver());
console.log('Saved: ' + value);
localforage.getItem(key).then(function(readValue) {
console.log('Read: ', readValue);
});
// Since this key hasn't been set yet, we'll get a null value
localforage.getItem(UNKNOWN_KEY, function(err, readValue) {
console.log('Result of reading ' + UNKNOWN_KEY, readValue);
});
});
});
// this is just for demonstration purposes
var originalConsoleLog = console.log;
function consoleLogProxy() {
originalConsoleLog.apply(console, arguments);
var htmlConsole = document.getElementById('htmlConsole');
if (htmlConsole) {
var message = Array.prototype.slice.apply(arguments, []).join(' ');
htmlConsole.innerHTML += '<li>' + message + '</li>';
}
}
console.log = consoleLogProxy;
Code snippet via https://javascript.plainenglish.io/javascript-apis-every-web-developer-should-know-fa9b36cc1ecf
Check out this codepen to see it working:
REFERENCES:
Another jist of that code - https://gist.github.com/famzil/7ab2dc38e851fb8fab6a948167f6c261#file-localforage-example-js
LocalForage - https://localforage.github.io/localForage/#installation
Web API for Storage - https://developer.mozilla.org/en-US/docs/Web/API/Storage
Cache API - https://developer.mozilla.org/en-US/docs/Web/API/Cache
Related TILs
Tagged: javascript