Problem saving information to localstorage via js

Asked

Viewed 483 times

1

Guys I’m trying to save my timer in the local storage but it is not saving it when I enter my console it does not appear follow my code HTML and JS

html

 <div id="timer">
          <span id="minutes"></span>:<span id="seconds"></span>
        </div>

JS

window.onload = function() {
  var access = localStorage.getItem('firstAccess');

  if(access == '') {
    var d = new Date();
    console.log(d);
    var time = localStorage.setItem('firstAccess', JSON.stringify(d));
    setTimer(time);
  }
  else {
     setTimer(access);     
  }
 function setTimer(time) {
     var timespan = countdown(time).toString();
     $('#minutes').html(timespan.minutes);
     $('#seconds').html(timespan.seconds);
 }
}

Console: inserir a descrição da imagem aqui

Here is where the set name Item that is firstAccess should appear inserir a descrição da imagem aqui

  • 1

    Some mistake in the console?

  • @Rafaelaugusto no more I will put the console print in the question but I do not know why not saved should have some problem in the code that I did not understand

  • I answered your question with error

2 answers

3


You’re doing it wrong. In this if

 if(access == '') {
    var d = new Date();
    console.log(d);
    var time = localStorage.setItem('firstAccess', JSON.stringify(d));
    setTimer(time);
  }

switch to that

 if(!access) {
    var d = new Date();
    console.log(d);
    localStorage.setItem('firstAccess', JSON.stringify(d));
    var time = localStorage.firstAccess
    setTimer(time);
  }
  • Thank you I’ll test here

  • @Kirito Beauty, then let us know if it worked

3

Change the line:

if(access == '') {

for:

if(access == null) {

This is the value default return method localStorage.getItem() to an unpopulated key.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.