Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment localStorage value by one

I am working on an attempted log in feature to our application. They fail three times it kicks them out altogether. To keep count of how many times they attempt I thought I would use localStorage because I can easily manipulate it. However, I am having trouble incrementing the value when they fail to authenticate themselves.

At the top, I am setting the localStorage variable

localStorage.setItem("attempts", "0")

and then if the server returns an error, I am trying to increment that value.

if(errorCode === 4936){
  var attempts = localStorage.getItem("attempts");
  localStorage.setItem(attempts++);
  console.log(attempts);
}

and obviously this is not working, but all I can find when I research is setting and getting the localStorage nothing about updating or changing. Any help would be wonderful!

like image 332
zazvorniki Avatar asked Sep 17 '25 16:09

zazvorniki


2 Answers

And in some cases you have to add ++ before attempts:

if (errorCode == 4936) {
  var attempts = parseInt(localStorage.getItem("attempts"));
  localStorage.setItem("attempts", ++attempts);
  console.log(attempts);
}
like image 69
Brennan Avatar answered Sep 20 '25 05:09

Brennan


According to the documentation of localstorage setItem only accept DomString (UTF-16 String). So the answer should be

if (errorCode === 4936) {
 var attempts = (parseInt(localStorage.getItem('attempts'))+1);
 localStorage.setItem("attempts", attempts.toString());
 console.log(attempts);
}
like image 25
Sohail Avatar answered Sep 20 '25 06:09

Sohail