Angular and Local Storage in strict mode

Viewed 395

I'm using Angular 12, which automatically adds strict mode to your projects. I was going through a tutorial to set up authentication in my project, but strict mode doesn't allow me to set it up as it is in the tutorial. I was going through this tutorial... https://www.positronx.io/full-angular-7-firebase-authentication-system/

This line of code doesn't work...

JSON.parse(localStorage.getItem('user'));

My text editor appears to like this alternative...

JSON.parse(localStorage.getItem('user') || '{}');

However, that alternative line doesn't appear to work as the tutorial intends for it to. For example...

If I use this getter function to check if the user is logged in, it gives me back true. Even if no one is logged in.

get isLoggedIn(): boolean {
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        return (user !== null) ? true : false;
    }

So I'm a little lost here and looking for a way to work with the localStorage in strict mode. I know that I can simply disable strict mode in Angular, but I was trying to not do that. Mind you, I'm still a bit of a novice programmer and maybe I'm even misunderstanding what this line of code is doing behind the scenes. Any help is appreciated.

3 Answers

argument type of parse method is string and localStorage.getItem('user') will return string or null

so your text editor suggest you to use Logical OR (||) for assign user property

it mean if JSON.parse(localStorage.getItem('user') return null use the second string mean '{}'

so your user property value is empty object and empty object is not null;

you can do this

const localUser = localStorage('user');
if(localUser) {
    const user = JSON.parse(localUser);
    return true;
} else{
    return false;
}

This is a better fix:

const user = JSON.parse(localStorage.getItem('user') || 'null')

Localstorage will return null if item is not found. try this :

get isLoggedIn(): boolean {
        const user = JSON.parse(localStorage.getItem('user') || null);
        return (user !== null) ? true : false;
    }
Related