DEV Community

Discussion on: Learn about using localStorage in Javascript and React

Collapse
 
rxliuli profile image
rxliuli

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
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gautham495 profile image
Gautham Vijayan

Thank you for including this code here!
I will surely include this in my workflow.

Collapse
 
rxliuli profile image
rxliuli

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.

Thread Thread
 
gautham495 profile image
Gautham Vijayan

I did not know, there was a option like this. I will check it out thanks.