Linux · April 25, 2019 0

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)