I am trying to save score of a game in local storage and then access it to display the saved score on my page i am trying this
const savedScores = [];
function saveRecord() {
localStorage.setItem("scores", JSON.stringify(timeTaken));
savedScores.unshift(JSON.parse(localStorage.getItem("scores")));
}
function veiwRecord() {
setBtnPopup((oldPopup) => !oldPopup);
console.log(savedScores);
return savedScores;
}
and then trying to display it like this
const scoreEl = savedSscores.map((score) => {
return <p> {score} </p>;
});
CodePudding user response:
var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));
//...
var storedNames = JSON.parse(localStorage.getItem("names"));
CodePudding user response:
All localStorage values are in string format, you need to parse the string array into array.
function veiwRecord() {
setBtnPopup((oldPopup) => !oldPopup);
savedScores = JSON.parse(localStorage.getItem("scores"));
console.log(savedScores);
return savedScores;
}
CodePudding user response:
You have to get the Item from localStorage as well in your veiwRecord method.
function set(){
var sendJSON = JSON.stringify(timeTaken);
localStorage.setItem('timeTaken',sendJSON)
}
function get(){
var getJSON = localStorage.getItem('timeTaken');
if (getJSON){
timeTaken = JSON.parse(getJSON)
}
}
