You should also use Proxy to simplify using them
function proxyStorage(storage) { const kSet = new Set([ 'storage', 'length', 'clear', 'getItem', 'setItem', 'removeItem', 'key', ]); return new Proxy(new WebStorage(storage), { get(target, p, receiver) { if (kSet.has(p)) { return Reflect.get(target, p, receiver); } return safeExec(() => JSON.parse(target.getItem(p.toString())), null); }, set(target, p, value, receiver) { if (kSet.has(p)) { return Reflect.set(target, p, receiver); } target.setItem(p.toString(), value !== undefined && value !== null ? JSON.stringify(value) : value); return true; }, }); } const store = proxyStorage(window.localStorage) store.name = 'liuli' console.log(store.name) // liuli
Thank you for including this code here! I will surely include this in my workflow.
No, you don't need it. If you use react, you should use react-use, which contains similar useLocalStorage hooks. If you plan to use it outside of react, you only need it.
I did not know, there was a option like this. I will check it out thanks.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You should also use Proxy to simplify using them
Thank you for including this code here!
I will surely include this in my workflow.
No, you don't need it. If you use react, you should use react-use, which contains similar useLocalStorage hooks. If you plan to use it outside of react, you only need it.
I did not know, there was a option like this. I will check it out thanks.