DEV Community

Cover image for Local Storage: Store data into the user’s browser
Khwaja Billal Siddiqi
Khwaja Billal Siddiqi

Posted on

1 1

Local Storage: Store data into the user’s browser

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay