Home > Enterprise >  React logic question: What does this mean?
React logic question: What does this mean?

Time:12-08

I'm new to React. I inherited a codebase I'm updating but am confused by this one line. I tried looking online but am still a bit confused.

Here is the line

this.state = { isLoggedIn: localStorage.getItem("isLoggedIn") ? true : false};

How is local storage being set here? Is it saying if localStorage.getItem("isLoggedIn") is true set the state variable isLoggedIn to false?

Thanks in advance.

CodePudding user response:

Local storage isn't being set. This is a conditional statement that is asking if localStorage contains an item "isLoggedIn" that has a truthy value (most likely "true", but that depends on the implementation). If this is the case, the state is being updated with {isLoggedIn: true}. Otherwise, it is updated with {isLoggedIn: false}.

CodePudding user response:

Local storage is not being set here. It's likely set elsewhere in your codebase when a user logs in or logs out. This code is reading local storage to initialize component state.

This is the equivalent code, split up and annotated for clarity:

// get the localStorage value if it exists
const storageValue = localStorage.getItem("isLoggedIn");

// if storageValue is truthy (not null, not empty, not false, not 0)
// set isLoggedIn to true, otherwise set it to false
const isLoggedIn = storageValue ? true : false;

// set state.isLoggedIn to the value of isLoggedIn.
this.state = { isLoggedIn: isLoggedIn };

CodePudding user response:

Another hint is the ternary operator. You can find more information about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

const moneyOnBank = 500;

const myMoney = moneyOnBank > 300 ? "Time to go for a lunch" : "Better to stay at home"

console.log(myMoney) => "Time to go for a lunch"

Basically, this.state contains a boolean, depending on whether a value is not null, empty or 0.

  • Related