DEV Community

loading...
Cover image for Local Storage: Store data into the user’s browser

Local Storage: Store data into the user’s browser

Khwaja Billal Siddiqi
・1 min read

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’);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

For getting back the data from the Local Storage, use getItem() method. This one only accepts the key parameter.

localStorage.getItem(‘name’);
Enter fullscreen mode Exit fullscreen mode

And if you converted array or object to a string, for retrieving, you should convert it back.

const selectedSeats = JSON.parse(localStorage.getItem(‘selectedSeats’));
Enter fullscreen mode Exit fullscreen mode

For removing a single item, use removeItem() method.

localStorage.removeItem(‘name’)
Enter fullscreen mode Exit fullscreen mode

And For clearing all items, use clear() method.

localStorage.clear()
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)