0

I want to be able to return true into a const if another const is inequal to null. Everything that I have tried on crashing react.

Most Promising:

const isActive = plugVal !== null

this keeps returning true even when plugVal is null.

With useState hook I tried:

const [isActive, setIsActive] = useState(false)

if(plugVal){
    setIsActive(true)
}
else{
    setIsActive(false)
}

this triggers to many re-renders

KeMeK
  • 25
  • 1
  • 6
  • 1
    Did you try logging the value of `plugVal`?? – TechySharnav Jun 04 '21 at 08:32
  • Try to use this !!plugVal Ideally plugVal !== null return false if plugVal is null Can you print the value of plugVal and Provide the image? [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/RQn0l.png – Mangesh Jun 04 '21 at 08:33
  • I would recommend `const value = plugVal ? "if true equals this" : "else equals this";` – Invizi Jun 04 '21 at 08:35
  • No not possible. `plugVal !== null` this will always return true if `plugVal` has any value other than `null`, you might be making some other mistake. – Vivek Bani Jun 04 '21 at 08:45
  • I used ```const isActive = plugVal ? true : false``` , and it logged out properly, but the code still didn't work. I went back and logged out ```isActive``` using the first method and it returned true, so the problem must be somewhere else in the code. Time for debug hell. yay. – KeMeK Jun 04 '21 at 08:58

2 Answers2

0

You can try the code of @Invizi using ternary operator. This other 2 cases also works fine.

const isActive = plugVal ? true : false

const isActive = Boolean(plugVal)

const isActive = !!plugVal
Khorne07
  • 199
  • 3
  • 12
0

The !! pattern using the ! operator is specifically just for this..

This topic covers it more in-depth

user3875913
  • 245
  • 2
  • 11