Danial
Danial

Reputation: 612

react.js uncaught typeerror

I'm trying to assign a variable's value based on another value in react.js. But it seems to be not working.

let user=localStorage.getItem('user');
let username="";
console.log(user);
if(user!==null || user!==undefined)
  username=JSON.parse(user).username;

console logs null, still it gives me: Uncaught TypeError: Cannot read property 'username' of null

Upvotes: 0

Views: 105

Answers (1)

Abito Prakash
Abito Prakash

Reputation: 4770

You can do something like this

let user = localStorage.getItem('user') ;
let username = (user && JSON.parse(user).username) || "";

This will set username to an empty string if user is undefined or null.

Upvotes: 1

Related Questions