DEV Community

Vinod Godti
Vinod Godti

Posted on

WebStorage APIs and it's uses in day to day coding

Web storage APIs are used to store data in the browser. Using web storage API we can store a minimum of 5MB data in desktop browsers.There is 2 mechanisms that are most commonly used in the modern web development world are Local storage and Session storage.

Why we should use Web storage?

  • To store user's specific data in their own browsers such as navigation history, Profile details and other data that are irrelevant to store in the server's database.

  • Some user's specific data loading from the server via API call may be very expensive in terms of time.

Let's dive into details

LocalStorage

In this web storage, we can store data in a key-value pair format.
Data stored in the web browser and data will persist even if the browser is closed. Data will remain as it unless and until we forcefully clear the data. We can store minimum of 5 MB or higher based on browser and platform.

Methods

Local storage has various methods to access, store, update and delete the data.

To save the data

window.localStorage.setItem("name","John Doe") 
Enter fullscreen mode Exit fullscreen mode

access the data

window.localStorage.getItem("name") //Output John Doe
Enter fullscreen mode Exit fullscreen mode

remove the data from local storage

window.localStorage.removeItem("name") //Removes the data 
Enter fullscreen mode Exit fullscreen mode

update the data

window.localStorage("name","Nicolas")
Enter fullscreen mode Exit fullscreen mode

To store the JSON data in local storage, We have to first convert JSON data into a string and then store it as localStorage accepts only string data.

let userData=JSON.stringify({"name":"Nicolas","email_id":"nicolas@abc.com"});
window.localStorage.setItem("userData",userData);
Enter fullscreen mode Exit fullscreen mode

To access the data, Again we have to convert a string into JSON data

let userData=window.localStorage.getItem("userData");
console.log(JSON.parse(userData));
Enter fullscreen mode Exit fullscreen mode

SessionStorage

sessionStorage is the same as localStorage except data will be available until the browser tab is closed. Data will be available in a particular session. It also can store a minimum of 5 MB data.

Methods

To save the data

window.sessionStorage.setItem("name","John Doe") 
Enter fullscreen mode Exit fullscreen mode

access the data

window.sessionStorage.getItem("name") //Output John Doe
Enter fullscreen mode Exit fullscreen mode

remove the data from local storage

window.sessionStorage.removeItem("name") //Removes the data 
Enter fullscreen mode Exit fullscreen mode

This web storage API also accepts string data only.

Top comments (0)