How to Use Web Storage (Session and Local Storage)
What is web storage?
Web storage is a storage that your browser (Chrome, Firefox, etc) provides so you could keep your data on your local computer. It can keep about 10MB of data. Web storage stores data in key-value pair format.
There is 2 kind of web storage.
- Session Storage. This kind of storage store your data until the browser or tab is closed.
- Local Storage. This kind of storage keeps your data permanent. The data still exists until you clear them.
When to use web storage?
Use web storage to keep user personalities like what themes they prefer or the language they used on your website. For temporary data, you could use session storage.
How to store the data inside web storage?
To interact with web storage, you need to write javascript code. Since web storage is a browser feature, you need to check whether your browser is supported or not.
To do that, you could use the following code :
If the type of object Storage is ‘undefined’, it means that the browser is not supporting web storage.
There are 4 methods you need to know in web storage.
Storage.setItem(key, value)
This is a method to store your data inside web storage. You could change Storage into localStorage or sessionStorage depending on what kind of storage you want to use. This is an example:
A thing you need to remember, web storage only supports data in string format, so if you want to keep data in an array or JSON format. You need to parse them to string. To do that, you could use JSON.stringify method.
Storage.getItem(key)
We can get the data using the keys we used before.
But remember, when we store the data, we keep them in string format. So when we get them, what we got is strings.
That's why we need to parse them to object and array using JSON.parse().
Now, this is what we got:
Storage.removeItem(key)
Right now we got 2 keys in localStorage. To remove we could use removeItem method.
This is the code:
Now, we only got one record left in localStorage:
Storage.clear()
You could use this method to clear all the records inside storage.
Storage.key(index)
This method will return a key from a certain index of record in storage. Storage has the ‘length’ property, so you know how many records you have stored, and you can get the key to getting the record using.
Okay. That's all about web storage. I’ll show you the implementation in other articles.
Thanks for reading my articles.