2

I have an application on a react. It has two modules: one that sets true value in localStorage, the second that runs the code and then sets false value to localStorage

I am trying to check as follows:

localStorage.setItem('update', false);

const checkUpdate = () => {
  if (localStorage.getItem('update') == 'true') {
    localStorage.setItem('update', false)
    alert('SUCCESFUL')
    return true
  } else {
    return false
  }
}


if (checkUpdate() == true) {
  console.log('OK')
} else {
  setTimeout(checkUpdate(), 2000)
}

It just does not work, and I can’t understand what my mistake is

VLAZ
  • 26,331
  • 9
  • 49
  • 67
A.Burdonskaya
  • 511
  • 1
  • 4
  • 27
  • 8
    `setTimeout(checkUpdate(), 2000)` will invoke `checkUpdate` immediately. If you want to only call it 2 seconds later, then remove the invocation: `setTimeout(checkUpdate, 2000)` – VLAZ Aug 22 '19 at 13:28
  • You have to get your types right... `true != 'true'` The first is a boolean, whereas the second is a string – devnull69 Aug 22 '19 at 13:30
  • 1
    @devnull69 pulling from localStorage always results in a string. That's why many devs opt for JSON in localStorage instead – Matt Aug 22 '19 at 13:32
  • @devnull69 not sure why this is relevant here - if you take anything from localStorage it's turned into a string – VLAZ Aug 22 '19 at 13:32
  • ... and there is no code that sets the value to true or 'true' in localStorage – devnull69 Aug 22 '19 at 13:32
  • @devnull69 sure, but OP's conditional is correct, they do not have the types wrong – Matt Aug 22 '19 at 13:33
  • It just hurts to see someone setting a boolean value to localStorage in the first place. I always tell people to only set strings to avoid complications and ambiguities – devnull69 Aug 22 '19 at 13:44
  • You might consider using a promise to reduce the potential of having multiple calls stack up as examples here https://stackoverflow.com/a/22707551/125981 – Mark Schultheiss Aug 22 '19 at 14:19

1 Answers1

2

setTimeout(checkUpdate(), 2000) will simply evaluate to setTimeout(false, 2000) on the first run because you are calling the function and not passing the referal to the setTimeout. The solution would be to use setTimeout(checkUpdate, 2000).

However, instead of always setting setTimeout(), you can use a setInterval() and when the condition meets, simply stop the interval with clearInterval().

localStorage.setItem('update', false);

const interval = setInterval(() => {
  if (localStorage.getItem('update') == 'true') {
    // stop the interval
    clearInterval(interval);
    alert('SUCCESSFUL');
  } else {
    console.log('not yet, retrying');
  }
}, 2000);

setTimeout(() => localStorage.setItem('update', true), 5000);

DEMO

silentw
  • 4,835
  • 4
  • 25
  • 45