Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3041

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T11:01:09+00:00 2024-11-26T11:01:09+00:00

javascript – Everything you always wanted to know about localStorage (but you were afraid to ask)

  • 61k

What is the localStorage?

The localStorage is a read-only property of the window interface that allows us to access the Storage for the Document’ origin (aka the browser). It let us save key-value pairs on the user browser. This was introduced on HTML 5 and everything it’s stored as a String, but I will show you how to save JSON objects.

Hold on, localStorage is read-only but let's store data? localStorage is read-only because it's immutable/cannot be overwritten se it's not possible to assign it to another value but we can use it to store data. If this sounds confusing for you don't worry adn keep reading and you will see how to use localStorage to store and retrieve data to the browser easily.

localStorage vs sessionStorage

The difference between localStorage and sessionStorage it’s the expiration date: the localStorage data will persist until:

  • We delete the data.
  • User clears the browser data.

localStorage data won’t persist if the user is using incognito or private browsing.

sessionStorage data gets expired each time the page it’s reloaded.

Update: regarding of the sessionStorage lifetime as @arandomdev points out:

sessionStorage does survive a page reload, as the browser assigns a session to the tab, and as long as its open, that session will not be cleared. Only when the tab or the browser gets closed that a new session will be assigned and the old sessionStorage will be cleared and a new one will be created.

How to write on localStorage

Data on localStorage is stored as key-value pairs and must always be String. It’s also possible to store and retrieve JSON objects with a little workaround. The function responsible for writing on the localStorage is the setItem function.

Image description

Example:

// Saving user access token localStorage.setItem('token', 'ksjakdkaugdka2i163mjbdja8y1'); 
Enter fullscreen mode Exit fullscreen mode

We can check that the informations has been saved by opening the console (f12) and checking the application tab under Local Storage:

Image description

Storing objects

In this case I’m saving the personal access token from a user, but what if I have to store an object with the user's details? Let’s try it:

// 1. We define an Object; const user = {name: 'John', surname: 'Connor', id: 2};  // 2. Try to store the Object: localStorage.setItem('user', user); 
Enter fullscreen mode Exit fullscreen mode

And now check the application tab:
Image description

Well it has stored ‘something’ but the content it’s not accessible so it’s useless and if this was an API response we would have lost the response. So how can we store objects in localStorage?

Though localStorage works only with strings so we can make it work transforming the object to a String:

// 1. We define an Object; const user = {name: 'John', surname: 'Connor', id: 2};  // 2. Transform the Object to String: const userString = JSON.stringify(user);  // 3. Store the object: localStorage.setItem('user', userString); 
Enter fullscreen mode Exit fullscreen mode

We can check it on the application tab:
Image description

The information is there, and more important, accessible.

How to read localStorage data

To read the localStorage data we use the getItem function and we need to know the key that keeps the data:

Image description

Example:

// Reading user access token from localStorage const token = localStorage.getItem('token'); console.log(token); 
Enter fullscreen mode Exit fullscreen mode

Image description

Reading objects

Now let’s retrieve the object we stored earlier using the same getItem function.

const user = localStorage.getItem("user"); console.log(`Welcome ${user.name} ${user.surname}`); 
Enter fullscreen mode Exit fullscreen mode

We read the localStorage and try to console log a greeting message using the object’s name and surname properties on console and this is what we get:

Image description

The console is returning undefined for the name and surname. Why? because what we stored is not an object it is a String. To read objects from localStorage we need to transform it from String to Object. Let’s try again:

// 1. Reading the object as string let user = localStorage.getItem("user");  // 2. Parsing the string to Object user = JSON.parse(user)  // 3. Now we can access the object properties. console.log(`Welcome ${user.name} ${user.surname}`); 
Enter fullscreen mode Exit fullscreen mode

Image description

How to find all localStorage keys

We can get an array with all the keys using Object.keys:

const keys = Object.keys(localStorage); console.log(keys); 
Enter fullscreen mode Exit fullscreen mode

Image description

How to remove data

To remove data from localStorage we have 2 options:

 Delete one item

We can use the function removeItem:

Image description

Example:

localStorage.removeItem("token"); 
Enter fullscreen mode Exit fullscreen mode

We can see that the token is no longer on the localStorage:

Image description

Delete all items

We can use the function clear to delete all existing items:

Image description

Example:

localStorage.clear(); 
Enter fullscreen mode Exit fullscreen mode

Drawbacks of localStorage

As I showed localStorage it’s very easy to use and that can lead us to misuses:

  • Don't store too much data on it as it has just 5MB per domain.
  • All data is easily accessible for the user and any script running on the page and that makes it insecure. So don’t store sensitive information.
  • Don’t be tempted to use it as a substitute for a database.

htmljavascriptprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.