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.
setItem()
methodAs the name signifies, the setItem()
method is used to store data in the HTML5 localStorage
.
window.localStorage.setItem(key, value);
key
: This is a unique identifier that can be used later to retrieve a value from localStorage
.value
: This is the data to be stored in the localStorage
.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.
myCountryInfo
. myCountryInfo
object into a string and use the setItem()
method to store it in the localStorage
.localStorage
data.