In modern web development, persistent data is always beneficial for a better user experience. In such scenarios, using local storage is a boon for all developers.
Local storage is the part of the web storage API that retains the data even when the user refreshes the page or closes the tab or browser. It is a feature that stores data in the user's browser by accepting data in key-value pairs. Hence, effectively using local storage persists data in an application and helps developers improve performance.
This blog will discuss how to use local storage in modern web applications. It will also explain storing, reading, and deleting data from local storage. We have also covered some examples to help you understand things better. So, let's start!
How Developers Can Use Local Storage?
Local storage provides different methods for interacting with it. Each method stores, reads and deletes data from local storage.
How to Store Data in Local Storage?
To store data in local storage, you should use the setItem() method that has two arguments: a key and a value.
localStorage.setItem(key, value)
Keytip: When you have to update the for the given key, use the same name in local storage. It will update it. Otherwise, the setItem() method creates a new key and assigns the given value when no such key exists in local storage.
How to Read Data from Local Storage?
You should use the getItem() method to retrieve and use data from the local storage. It takes only a key as an argument.
localStorage.getItem(key)
The method returns the key's value from local storage. However, if no such key exists, it will return null.
Does it seem too simple? The following section covers how to store and read complex data.
How to Store and Read Complex Data in Local Storage?
Local storage works only with strings when storing data.
To store complex values, you should create objects or arrays (a string representation of the value). You can use the JSON.stringify() method to convert it to a string representation.
// Store data in local storage.
const userObj = {
username = "Maria",
email: "maria@mail.com"
}
localStorage.setItem('user', JSON.stringify(userObj))
// Fetch data from localstorage.
const storedUserData = localStorage.getItem('user')
if (storedUserData) {
const userData = JSON.parse(storedUserData)
// You can use userData here...
} else {
console.log('No User data found')
}
Explanation:
The JSON.stringify() method first converts the userObj object into a string representation before sending it to local storage.
When you want to retrieve data from local storage, the JSON.parse() method changes it from its string representation to its original form.
However, to avoid errors, you should first check if there is data for 'user' in local storage before using the JSON.parse() method. This is because JSON.parse() applies a null value if data does not exist in local storage, which will result in an error.
How to Delete Data from Local Storage?
There are two methods for deleting data from local storage: the removeItem() method and the clear() method.
You should use the removeItem() method to delete a single item from local storage. It takes a key as an argument. It then deletes the corresponding key-value pair in local storage.localStorage.removeItem(key)
Or, you can use the clear() method to delete all data from the local storage. This method deletes all key-value pairs in the local storage for the current domain.
localStorage.clear()
How to Get the Name of Key in Local Storage?
You should use the key() method to get the name of a key in local storage. The method takes a number as an argument and returns the name of the key at that specified index.
localStorage.key(0)
It returns the name of the key at index 0. If no key exists at the specified index, it returns null.
An Example to Understand Things Better
To understand things better, we will take an example of saving the user's name in local storage and the age in session storage. (Here, we are considering that our readers know how to use session storage.)
<!-- HTML -->
<body>
<label class="userName"></label>
<input type="text" class="name" placeholder="Enter name here"/>
<button class="saveNameBtn">Save Name</button>
<br />
<label2 class="userAge"></label2>
<input type="text" class="age" placeholder="Enter age here"/>
<button class="saveAgeBtn">Save Age</button>
</body>
Explanation: Here, we take two label elements for userName and userAge for two input elements: name and age. Each input has an associated button for saving the data. The querySelector method helps us select the various elements.
const userNameText = document.querySelector(".userName");
const userAgeText = document.querySelector(".userAge");
const saveNameButton = document.querySelector(".saveNameBtn");
const saveAgeButton = document.querySelector(".saveAgeBtn");
Code for local storage to get the name value
Here, we are first writing code for the following:
Getting the value of the name (input)
Setting it as the textContent of userNameText
Using the setItem() of local storage to save the userName value in local storage
saveNameButton.addEventListener("click", () => {
const userName = document.querySelector(".name").value;
userNameText.textContent = userName;
localStorage.setItem("name", userName);
})
Now, to get the name value from local storage, use the following code:
function displayUserName () {
const nameFromLocalStorage = localStorage.getItem("name");
if (nameFromLocalStorage) {
userNameText.textContent = nameFromLocalStorage;
} else {
userNameText.textContent = "No name data";
}
}
displayUserName();
Explanation:
Using displayUserName function to get the name from local storage with the getItem() method
If the value exists (in local storage), the code sets it as the textContent of the userNameText element.
If not (when null or nonexistent), we set textContent to the string "No name data in local storage".
Code for session storage to get the age value
Here is the code to get the age value data:
saveAgeButton.addEventListener("click", () => {
const userAge = document.querySelector(".age").value
userAgeText.textContent = userAge
sessionStorage.setItem("age", userAge)
})
function displayUserAge () {
const ageFromSessionStorage = sessionStorage.getItem("age")
if (ageFromSessionStorage) {
userAgeText.textContent = ageFromSessionStorage
} else {
userAgeText.textContent = "No data of age"
}
}
displayUserAge()
Here, we are using session storage instead of local storage. Also, the setItem and getItem methods work for session storage. The name data from local storage persists even if you close the tab; however, the age data from session storage is cleared once the page closes, as per their respective identities.
Conclusion
Local storage is a feature in modern web architecture that helps you save and persist data between browser sessions. Compared to traditional cookies, it offers larger storage capacities. It doesn't rely on server-side processes, reduces the need for frequent server requests, and improves performance.