Last active
May 13, 2021 10:22
-
-
Save ross-u/55c95e54bbfd7f992bbee92a45478172 to your computer and use it in GitHub Desktop.
Using localStorage - example
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
// An array that contains data (array of objects) | |
// to be stored in the localStorage | |
const score = [ | |
{ name: 'Anna', score: 4120 }, | |
{ name: 'Bob', score: 1245 }, | |
{ name: 'Sarah', score: 5699 }, | |
{ name: 'Marc', score: 3452 }, | |
]; | |
// Stringify the data before storing in localStorage | |
const scoreStringified = JSON.stringify(score); | |
console.log('scoreStringified', scoreStringified); | |
// Save the string data to localStorage | |
// localStorage.setItem('keyName', stringValue) | |
localStorage.setItem('score', scoreStringified); | |
console.log('localStorage', localStorage); | |
// Retrieve the stored string from localStorage | |
// localStorage.getItem('keyName') | |
const scoreString = localStorage.getItem('score'); | |
console.log('scoreString', scoreString); | |
// Convert the retrieved string data to array or object | |
// using JSON.parse() | |
const scoreArray = JSON.parse(scoreString); | |
console.log('scoreArray', scoreArray); | |
// Update the array by pushing new object to it | |
scoreArray.push({ name: 'Uros', score: 145 }); | |
// Stringify the updated array before storing in localStorage | |
const updatedScoreString = JSON.stringify(scoreArray); | |
localStorage.setItem('score', updatedScoreString); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment