Created
December 19, 2020 23:16
-
-
Save DoctorDerek/6fe4fc06374953be46b496ea37fabded to your computer and use it in GitHub Desktop.
Can We Store JavaScript Objects in LocalStorage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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