Last active
January 27, 2021 08:36
-
-
Save Avi-E-Koenig/8a4884c4af848e20175a48910e4c1629 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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