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)

One thought on “How to store/retrieve object in localStorage

Leave a Reply

Your email address will not be published. Required fields are marked *