How to store objects in HTML5 localStorage
Overview
The localStorage property of the interface window allows us to access the Storage object and store data in it.
It doesn't have an expiration time. Therefore, the data stored in it will persist until explicitly removed. Even closing the browser won't remove the localStorage data.
To use the localStorage in a web application, there are a couple of methods to store, retrieve, clear, and remove data. Out of them, we'll explore the setItem() method in this shot.
The setItem() method
As the name signifies, the setItem() method is used to store data in the HTML5 localStorage.
Syntax
window.localStorage.setItem(key, value);
Parameters
key: This is a unique identifier that can be used later to retrieve a value fromlocalStorage.value: This is the data to be stored in thelocalStorage.
Storing an object in localStorage
The values that are stored in the localStorage should be of the string datatype. To store an object or an array in the localStorage, we first need to convert it to string using the JSON.stringify() method. Next, we can pass it as the value in the setItem() method.
Example
Explanation
- Lines 2–5: We create an object,
myCountryInfo. - Line 9: We make the
myCountryInfoobject into a string and use thesetItem()method to store it in thelocalStorage. - Line 12: We retrieve the
localStoragedata.