Localstorage in Javascript: a better and easier way using getters and setters

Mark Caggiano
2 min readSep 13, 2022

We all know that in JS we can use localStorage to persist data between pages reload like this:

let myItem = localStorage.getItem('item') ?? null;// Do stuff
localStorage.setItem('item', 'data');
// Page refresh
console.log('myItem: ', myItem); // Prints data

Yes but is so unelegant and verbose.

And what if we want to store more structurated data between page reloads ? It becomes even more verbosly…

let myItem = JSON.parse(localStorage.getItem('item')) ?? {};// Do stuffmyItem = await axios.get('endpoint', data);
localStorage.setItem('item', JSON.stringify(myItem));
// Page refresh
console.log('myItem: ', myItem); // Prints data from axios

Everytime we have to write 2 lines of code instead of one, and this can lead to verbously unreadable code and bugs.

So what we can do ?

Using Getters And Setters To Solve The Issue

The solution is really straightforward: we just use a javascript builtin: getters and setters.

Getters and setters method let us define our an object property should be treaten when read or wrote, for example:

const obj = {
p: '',
get prop() {
return 'prop'
},
set prop(value) {
this.p = value
}
}
console.log('obj.prop: ', obj.prop); // Prints 'prop'obj.prop = 'Asdrubale'
console.log('obj.prop: ', obj.prop; // Still prints 'prop'
console.log('obj.p: ', obj.p); // Prints 'Asdrubale'

So we can define a store helper that handles the json stuff for us:

function localStorageHelper(key) {
return {
get [key]() {
return JSON.parse(localStorage.getItem(key)) ?? null
},

set [key](data) {
localStorage.setItem(key, JSON.stringify(data))
},

has(key) {
return key in localStorage
},

del(key) {
return localStorage.removeItem(key)
}
}
}

--

--