How to store/retrieve object in localStorage


Local storage can store string data only, what if you want to store an object?

Answer to above question is, convert object into string using “JSON.stringify()”

const user = {
   name : "Tofeeq",
   email: "tofeeq3@gmail.com"
}

const objString = JSON.stringify(user)
localStorage.setItem('user', objString)

 

How to get object back from localStorage?

You can get user back from localStorage and convert it back to object using “JSON.parse()”

 

const userString = localStorage.getItem('user')
const user = JSON.parse(userString)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s