0
\$\begingroup\$

So I have this game and I would like to have a save function. Here is my code below:

function SaveData() {
  localStorage.setItem('save', score);
  localStorage.setItem('save', btoa(JSON.stringify(score)));  
}
function LoadData() {
  score = window.localStorage.getItem('save');
  document.getElementById('demo').innerHTML = score;
}
window.onload = function()  {
LoadData();
} 

When it loads it does not use the storage or it says Not a Number (NaN)

\$\endgroup\$
2
  • 2
    \$\begingroup\$ What is the issue you're facing? \$\endgroup\$
    – Vaillancourt
    Nov 8, 2019 at 1:24
  • \$\begingroup\$ Can you give us an example of the data you're storing just so we can ensure that the data type isn't causing the issue \$\endgroup\$
    – Ameer
    Nov 16, 2019 at 14:06

2 Answers 2

0
\$\begingroup\$

Ok, so let's assume you have a DOM element in which you display the score, and start with that. So, the first time the user will arrive on the game, the score will be "0" (you will probably have something to calculate it and that's not the scope of this answer, let's focus on the load and save parts for now. I'll write the save function in this way:

function SaveData(score) {  
  localStorage.setItem('save', btoa(score));  
}

While, the load function could be like:

function LoadData() {
  var score = window.localStorage.getItem('save');
  if (score === null){
    score = 0;
  }else{
    score = atob(score);
  }
  document.getElementById('demo').innerHTML = score;
}

I've used the btoa an atob, but they are unnecessary to save just a number, but since you used them I suppose there will be a reason, I deleted the JSON.stringyfy (and not added the parse) because that's totally unnecessary and could be trivial, because you will end up with an object (or an error)

\$\endgroup\$
0
\$\begingroup\$

Your code here has several issues. Your score will be NaN if nothing has been saved (the first time the game is played). Then when you try to save that NaN, it remains NaN. Also, you don't convert it back from btoa and JSON.stringify (which is entirely unnecessary in the first place).

In the code you linked, you go back and forth between score being a number and it being a DOM node (with .value).

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .