DEV Community

Ertan Özdemir
Ertan Özdemir

Posted on

How to add an object to localStorage?

In this note I will show you how to insert an object to localStorage

In some situations you may want to store data in local storage or session storage as an object. So how can you achieve this?

Assume that we have an object and this object stores some tokens.



const tokens = {
token: "meowmeow",
anotherToken: "woofwoof"
}


Enter fullscreen mode Exit fullscreen mode

Writing to localStorage

To set a localStorage item we have to use localStorage.setItem( ) method. This method takes two parameters, key and value. key is the name of our local storage item and the value is basically its value.

We cannot directly store objects in localStorage or session storage. Therefore we have to convert them into JSON string. To do that we have very handy method called JSON.stringify(value). value parameter is going to be object that we want to convert into JSON string. In this example value is tokens



JSON.stringify(tokens)


Enter fullscreen mode Exit fullscreen mode

We learned how to convert object into JSON string. Now, let's add this JSON string to our localStorage



const tokens = {
token: "meowmeow",
anotherToken: "woofwoof"
}

localStorage.setItem("tokens", JSON.stringify(tokens))



Enter fullscreen mode Exit fullscreen mode

If you check your local storage, you can see that your object has been successfully added.

Image description


Reading from localStorage

To read an object from localStorage, we have another handy method called JSON.parse( ). This method helps us to convert JSON string into JavaScript object. But first, we have to get the object from local storage.



const localStorageItem = localStorage.getItem("tokens")
const tokenObject  = JSON.parse(localStorageItem)


console.log(tokenObject)

/*
{
token: "meowmeow",
anotherToken: "woofwoof"
}
*/



Enter fullscreen mode Exit fullscreen mode

Top comments (0)