I am trying to save the 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>;
});
You can store arrays and other object types in localStorage using "JSON.stringify", as strings are the only data types that localStorage accepts.
var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));
//...
var storedNames = JSON.parse(localStorage.getItem("names"));
Then you can retrieve stored data with JSON.parse so you can use your array, object etc...
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;
}
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)
}
}