Today I Learned - Rocky Kev

TIL LocalForage, a small js library for caching

POSTED ON:

TAGS:

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:

// 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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.