DEV Community

Full of Dev
Full of Dev

Posted on • Originally published at onebite.dev

Working With Object In Localstorage

We all love localstorage, no database needed to store simple things for our user.

But what if the data is more than a string or number?

Let’s see how to store and read object in localstorage?

How to store object in localstorage

We need to turn json into a string with JSON.stringify

localstorage.setItem(key, JSON.stringify(val));
Enter fullscreen mode Exit fullscreen mode

How to read/retrieve object from localstorage

We need to parse into json with JSON.parse

JSON.parse(localstorage.getItem(key))
Enter fullscreen mode Exit fullscreen mode

Bonus: Helper for read and write objects in localstorage

function getObjectLS(key) {
    return JSON.parse(localStorage.getItem(key))
}

function setObjectLS(key, val) {
    localStorage.setItem(key, JSON.stringify(val));
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)