2

I have been searching about this many hours still nothing solved my problem:can't check if a key does exist in the localStorage.

In my chat application,Once the user opens a new tab, I want to check if there is registered user already,I do that using localStorage variable in the following way:

window.addEventListener('load', function () {
    var s=localStorage.getItem("localStor");
    if (s === null){
        console.log("is null"); //does not enter here
    }else{
        console.log(s); // prints [object *O*bject]
        console.log(JSON.parse(s).name);  //getting an error (see below)
    } 
}, false);

When parsing I get the error:

Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>)

The first place I set localStor item in the localStorage is only after registering and it is inside a function that is called only when clicking on a button HTML element.But logically it should not enter in the else from the first place.

Any idea why this isn't working? any help is appreciated.

user8244016
  • 929
  • 3
  • 12
  • 24
  • validate your JSON and write all this in `try..watch` – vsync Sep 06 '17 at 16:00
  • @vsync nothing changed , I tried to alert the error but nothing happened – user8244016 Sep 06 '17 at 16:05
  • You're doing it correctly, as mentioned here: https://stackoverflow.com/questions/3262605/how-to-check-whether-a-storage-item-is-set I suspect there's something about your `JSON.parse()` in which the `name` property is not valid... or something like that. Try just logging the `JSON.parse(s)` result to see what your value looks like. – Marc Sep 06 '17 at 16:10
  • @Marc , my wuestion is not about the error ,please read it again – user8244016 Sep 06 '17 at 16:12
  • Most likely the value you're trying to parse is `"[object Object]"`, i.e. it is incorrectly set in the first place. The value stays in the local storage until you remove it. You've set it during testing, and it is always found. – Teemu Sep 06 '17 at 16:12
  • I read your question. I think you're setting this value and don't know it. It has to be there unless you're questioning the validity of the javascript `getItem()` code. And then you're getting an error when parsing the value you didn't know you set. – Marc Sep 06 '17 at 16:13
  • I only mentioned the error to give a full view of what happening ,my problem is that the if condistion must return true , but it returns false! – user8244016 Sep 06 '17 at 16:15
  • 1
    Yes, @user8244016, I understand your problem. I maintain that your item lives in localStorage, otherwise `getItem()` would return a null. Here's a little about when localStorage gets cleared: https://stackoverflow.com/questions/8537112/when-is-localstorage-cleared – Marc Sep 06 '17 at 16:16

2 Answers2

3

It looks like you forgot to serialize your object prior to storing in localStorage, you need to use

localStorage.setItem('localStor', JSON.stringify(yourObject));

Then this should work as expected.

Since it appears that there is a rogue item in your localStorage, you may want to reset localStorage and try again:

localStorage.clear()
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • my goal is not to set an item in the local storage , I cant check if an item exists in the localStorage – user8244016 Sep 06 '17 at 16:06
  • I understand that, but the problem is that the object isn't being set into `localStorage` correctly, therefore your `JSON.parse()` call is failing. – Rob M. Sep 06 '17 at 16:07
  • it shouldn't enter the else statement in the first place,I'm not asking about the error.. – user8244016 Sep 06 '17 at 16:09
  • 1
    I don't understand your question then, you are already correctly checking if an item exists in `localStorage`. The item is not `null`, therefore your code is processing the `else` block. It sounds like your code might be setting the `localStorage` item when you don't want to. FYI, `localStorage` values _aren't unique to tabs_, they are unique to domains. If you want it to reset for each new tab you need to use `sessionStorage` – Rob M. Sep 06 '17 at 16:15
  • but the item should be null , I can't figure out why it isn't? as I mentioned the first place setting a value to localStor is when clicking a button – user8244016 Sep 06 '17 at 16:19
  • 2
    Perhaps you should post that code, because it seems like something else might be happening. If that isn't the case, you may want to just clear `localStorage` and try again – Rob M. Sep 06 '17 at 16:20
-1

You need to use JSON.stringify to serialize your object before putting it into local storage.

Did your code put the localStor object in local storage in the first place? If so, when you do that it needs to be serialized before being put in so that it can later be successfully read using JSON.parse.

If localStorage.getItem does not return null, then the key you are requesting is in localStorage. Its return value doesn't lie. The fact still remains that you are getting a non-serialized object back from the getter, so you need to figure out where that object was erroneously put into localStorage.

hsotweelvl
  • 85
  • 5
  • my goal is not to set an item in the local storage , I cant check if an item exists in the localStorage – user8244016 Sep 06 '17 at 16:06
  • Did your code put the `localStor` object in there in the first place? If so, when you do that it needs to be serialized before being put in so that it can later be successfully read using `JSON.parse`. – hsotweelvl Sep 06 '17 at 16:08
  • "Did your code put the localStor object in there in the first place" ,No it doesn't ,please read the question again – user8244016 Sep 06 '17 at 16:10
  • Hmm. Well if `localStorage.getItem` does not return `null`, then the key you are requesting is in `localStorage`. Its return value doesn't lie. The fact still remains that you are getting a non-serialized object back from the getter, so you need to figure out where that object was erroneously put into localStorage. – hsotweelvl Sep 06 '17 at 16:14