To avoid the long process of store a user's simple activities in the database is to store them in his/her browser.
Local Storage is key-value pairs and it’s read-only. So you can access Local Storage in Javascript via the window.localStorage property.
For storing data you need to use setItem() which takes two parameters: a key and a value.
localStorage.setItem(‘name’, ‘Jonh Doe’);
If you want to store an array or an object you need to convert them into a string.
const seatsIndex= [1,4,5]
localStorage.setItem(‘selectedSeats’, JSON.stringify(seatsIndex));
For getting back the data from the Local Storage, use getItem() method. This one only accepts the key parameter.
localStorage.getItem(‘name’);
And if you converted array or object to a string, for retrieving, you should convert it back.
const selectedSeats = JSON.parse(localStorage.getItem(‘selectedSeats’));
For removing a single item, use removeItem() method.
localStorage.removeItem(‘name’)
And For clearing all items, use clear() method.
localStorage.clear()
Web browsers also have another storage called Session Storage and the difference between them is the Local Storage has no expiration date so the data not be deleted when the browser refreshed or closed, but the Session Storage deletes data when the tab is closed.
note: do not store user’s sensitive data in Local Storage.
Top comments (0)