Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save DoctorDerek/6fe4fc06374953be46b496ea37fabded to your computer and use it in GitHub Desktop.

Select an option

Save DoctorDerek/6fe4fc06374953be46b496ea37fabded to your computer and use it in GitHub Desktop.
Can We Store JavaScript Objects in LocalStorage
// Read in old localStorage
const pizza = JSON.parse(localStorage.getItem("pizza"))
if (!pizza) {
console.log("No pizza was found in localStorage.")
console.log("Let's save {pizza: 'πŸ•'} to localStorage.")
console.log("Your slice of pizza will be waiting for you!")
// You can't save the object directly to localStorage:
// window.localStorage.setItem('pizza', {pizza: "πŸ•"})
// Instead, call JSON.stringify() on the object first:
const freshPizza = JSON.stringify({ pizza: "πŸ•" })
window.localStorage.setItem("pizza", freshPizza) // Yum!
} else {
console.log("Here's your fresh slice of pizza!")
console.log(pizza) // Output: Object { pizza: "πŸ•" }
console.log("It was waiting for you in localStorage.")
console.log("I'll remove it from localStorage now.")
window.localStorage.removeItem("pizza")
// Or you could clear localStorage completely with:
// window.localStorage.clear() // Remove all items
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment