Skip to content

Instantly share code, notes, and snippets.

@Avi-E-Koenig
Last active January 27, 2021 08:36
Show Gist options
  • Save Avi-E-Koenig/8a4884c4af848e20175a48910e4c1629 to your computer and use it in GitHub Desktop.
Save Avi-E-Koenig/8a4884c4af848e20175a48910e4c1629 to your computer and use it in GitHub Desktop.
// see: https://davidwalsh.name/javascript-proxy-with-storage
function getStorage() {
return new Proxy(window.localStorage, {
// just a helper to see if value is valid json ie stringified obj or array
set: (obj, prop, value) => {
value !== null && typeof value === 'object'
? obj.setItem(prop, JSON.stringify(value))
: obj.setItem(prop, value);
console.log(`${prop} added to localstorage!๐Ÿ˜€`);
},
get: (obj, prop) => {
isJson = (str) => {
if (typeof str !== 'string') return false;
try {
const result = JSON.parse(str);
const type = Object.prototype.toString.call(result);
return type === '[object Object]' || type === '[object Array]';
} catch (err) {
return false;
}
};
const value = obj.getItem(prop);
if (isJson(value)) {
const parsed = JSON.parse(value);
return parsed;
}
return value;
},
});
}
const StorageRef = getStorage(localStorage);
StorageRef.newProp = 'see what happens in console.log ๐Ÿ˜€';
console.log('StorageRef.newProp', StorageRef.newProp);
StorageRef.something = { a: 1, b: ['s'] };
console.log('StorageRef.somethin', StorageRef.something);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment