localStorage, or IndexedDB, you can use a proxy to make the API much easier to work with!
A very basic usage of the Proxy API is as follows:
/* const proxy = new Proxy(, get: (obj, prop) => ... , set: (obj, prop, value) => ... , // more props here ); */ // This basic proxy returns null instead of undefined if the // property doesn't exist const proxy = new Proxy(, get: (obj, prop) => return prop in obj ? obj[prop] : null; ); // proxy.whatever => null
The localStorage API is easy enough to use but employing a Proxy allows us to use the familiar object syntax and eventually even swap out the storage type without any other part of your code being effected.
function getStorage(storage, prefix) return new Proxy(, set: (obj, prop, value) => // obj[prop] = value; storage.setItem(`$prefix.$prop`, value); , get: (obj, prop) => // return obj[prop]; return storage.getItem(`$prefix.$prop`); , ); // Create an instance of the storage proxy const userObject = getStorage(localStorage, "user"); // Set a value in localStorage userObject.name = "David"; // Get the value from localStorage const name = userObject;
Note: The code above is a very simplistic example — you’d also want to add methods for deleting from the object, as well as try/catch to prevent storage errors!
You could swap
And I’m not the only one that loves this pattern. Firefox DevTools debugger uses this pattern to abstract the IndexedDB API for storing breakpoints, tabs, and other preferences!