3

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.

9
  • validate your JSON and write all this in try..watch Commented Sep 6, 2017 at 16:00
  • @vsync nothing changed , I tried to alert the error but nothing happened Commented Sep 6, 2017 at 16:05
  • You're doing it correctly, as mentioned here: stackoverflow.com/questions/3262605/… 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. Commented Sep 6, 2017 at 16:10
  • @Marc , my wuestion is not about the error ,please read it again Commented Sep 6, 2017 at 16:12
  • 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: stackoverflow.com/questions/8537112/… Commented Sep 6, 2017 at 16:16

3 Answers 3

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() 
Sign up to request clarification or add additional context in comments.

6 Comments

my goal is not to set an item in the local storage , I cant check if an item exists in the localStorage
I understand that, but the problem is that the object isn't being set into localStorage correctly, therefore your JSON.parse() call is failing.
it shouldn't enter the else statement in the first place,I'm not asking about the error..
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
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
|
1

this is error statement

Error while working with localStorage: todos not exist ReferenceError: localStorage is not defined at _TodosComponent (/Users/jonty/angular/cwh-todo-list/src/app/MyComopnents/todos/todos.component.ts:20:24) at NodeInjectorFactory.TodosComponent_Factory (/Users/jonty/angular/cwh-todo-list/src/app/MyComopnents/todos/todos.component.ts:60:5) at getNodeInjectable (/Users/jonty/angular/cwh-todo-list/node_modules/@angular/core/fesm2022/core.mjs:4392:44) at createRootComponent (/Users/jonty/angular/cwh-todo-list/node_modules/@angular/core/fesm2022/core.mjs:15619:35) at ComponentFactory.create (/Users/jonty/angular/cwh-todo-list/node_modules/@angular/core/fesm2022/core.mjs:15483:25) at ViewContainerRef2.createComponent (/Users/jonty/angular/cwh-todo-list/node_modules/@angular/core/fesm2022/core.mjs:19994:47) at _RouterOutlet.activateWith (/Users/jonty/angular/cwh-todo-list/node_modules/@angular/router/fesm2022/router.mjs:2415:31) at ActivateRoutes.activateRoutes (/Users/jonty/angular/cwh-todo-list/node_modules/@angular/router/fesm2022/router.mjs:3025:28) at eval (/Users/jonty/angular/cwh-todo-list/node_modules/@angular/router/fesm2022/router.mjs:2979:12) at Array.forEach (<anonymous>) 

I got the error even though I handle exception with the try-catch blog. This error has been created because my variable does not exist so it can't be null. Here localItem === undefined

todos:Todo[]; localItem : string; constructor() { try { this.localItem = localStorage.getItem("todos"); if (this.localItem === null ) { this.todos = []; } else { this.todos = JSON.parse(this.localItem); } } catch (error) { // Handle the error here console.error('Error while working with localStorage: todos not exist', error); // You can provide a default value or take other appropriate actions this.todos = []; } } 

instead put localitem variable into if statement

if (!this.localItem ) { this.todos = []; } else { this.todos = JSON.parse(this.localItem); } 

Comments

-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.

4 Comments

my goal is not to set an item in the local storage , I cant check if an item exists in the localStorage
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.
"Did your code put the localStor object in there in the first place" ,No it doesn't ,please read the question again
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.