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.

--

--