0

I need to check if there is any key in localStorage This code did not work

    if (localStorage.user === undefined) {
      alert('There is no key!'); 
    }
  • Possible duplicate of [How to check whether a Storage item is set?](https://stackoverflow.com/questions/3262605/how-to-check-whether-a-storage-item-is-set) – coturiv Dec 16 '17 at 11:41
  • Or also look here and add your own code: https://stackoverflow.com/questions/17745292/all-local-storage-items – Oliver F. Dec 16 '17 at 11:50

2 Answers2

2
if (Object.keys(localStorage).length === 0) {
  alert('There is no key!'); 
}
codejockie
  • 9,020
  • 4
  • 40
  • 46
0

You need to use getItem

if (localStorage.getItem("user") === null) {
    alert('Não há chave!'); 
}

EDIT You can check if the localstorage is empty by

if (localStorage.length == 0)
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396