A simple way to have a synced Set in localStorage

We can extended the Set class to serialize and store the information in LocalStorage and keep the data in sync by overriding the add and delete methods of the Set. Like so:

class localStorageSet extends Set{
    constructor(key){
        super()
        this.key = key
    }


    add(val, raw=false){
        const r = super.add(val)
        if(r && raw == false) this.saveToLocalStorage()
        return r
    }

    delete(val) {
        const r = super.delete(val)
        if(r) this.saveToLocalStorage()
        return r
    }

    saveToLocalStorage(){
        window.localStorage.setItem(this.key, JSON.stringify([...this]))
    }

    // populate set from localStorage
    get(){
        let self = this
        const storedItem = JSON.parse(window.localStorage.getItem(this.key))

        if(storedItem){
            storedItem.forEach(item => {
                self.add(item, true)
            });
        }
        return self                
    }
}

We can then use it by creating an instance with the key we want to store the Set:

let votedFor = new localStorageSet('votedFor')

Then add or delete the keys normally:

votedFor.add('item-1')
votedFor.add('item-2')
votedFor.add('item-3')

votedFor.delete('item-2')

We can sync the latest state on LocalStorage with what’s on memory by using the get method:

votedFor.get()
votedFor.add('item-4')

Loading back the Set into memory in a different location for eg:

let votedFor = new localStorageSet('votedFor')

votedFor.get()
votedFor.add('item-5')
Topics: JS