DEV Community

Afikode Olusola Emma
Afikode Olusola Emma

Posted on

Using localStorage to store data in the browser

It is possible to save data handled by web application without building a database. Two of the properties that allows this to happen are the localStorage and sessionStorage. Both of these are Web Storage APIs mechanisms which basically allow data to be stored in key-value pair. So basically, you have something really similar to the JavaScript object. They do not change after page loads or refresh. The focus of this article is on localStorage.

localStorage
Whenever data is saved to the localStorage, it remains intact even after the browser has been closed. This means that data in the localStorage is not affected by the closing and restarting of the browser. To save data in the localStorage, the setItem() method can be used.
Example: localStorage.setItem("name", "value");

If the value passed is an array, you will have to transform it to a string by using the JSON.stringify() method.

Example: localStorage.setItem("name", JSON.stringify(object));
The name and value represents the key and value of the item being stored.

Note: The Web APIs key-value pair objects are always in strings, hence the need for the second example above.
Now to retrieve item stored in the database, the getItem() method comes in handy.
Example: localStorage.getItem("name");
Again, the data retrieved need to be transformed from strings into an object, and we will be using another method called the JSON.parse().
Example: JSON.parse(localStorage.getItem('name'));

To remove item from the localStorage, the removeItem() method is used. It takes the key of the item to be removed as below:
Example: localStorage.removeItem("name");

Lastly, you can clear the storage by using the clear() method on the localStorage object.
Example: localStorage.clear();

Watch out for my next article as I will be writing about sessionStorage() and its respective methods.

Top comments (0)