crimsonpython24
crimsonpython24

Reputation: 2383

React/Javascript Comparison Operator Not Working

Somehow I couldn't get my comparison operators working. I have the following piece of code:

function handleNotifClickRemind(key) {
  localStorage.setItem('no_remind_change_pwd', true);
  notification.close(key);
}

// ...

<Button outline size="small" onClick={() => handleNotifClickRemind(key)}>
  Dont remind me
</Button>

// ...

console.log(localStorage.getItem('no_remind_change_pwd'));
function another_func(data) {
  if (localStorage.getItem('no_remind_change_pwd') != true) {
    openNotification('topRight');
  }
}

When I clicked the "Don't remind me" button, handleNotifClickRemind was triggered because the log output on the third section prints true. However, openNotification was still being triggered. Can anyone please help?

P.S. I didn't initialize the value, I just let no_remind_change_pwd be null.

Thanks in advance.

Upvotes: 0

Views: 1278

Answers (2)

Satish Chandra Gupta
Satish Chandra Gupta

Reputation: 3351

  1. It's always good practice to use triple comparison operator like === or !==.
  2. localStorage.getItem() return data in String format so if you want to compare with some boolean then first convert it to boolean. By Boolean(localStorage.getItem('no_remind_change_pwd')).

function another_func(data) {
  if (Boolean(localStorage.getItem('no_remind_change_pwd')) !== true) {
    openNotification('topRight');
  }
}

Hope this should clear your understanding.

Upvotes: 1

Maradox
Maradox

Reputation: 640

All you've saved in localstorage are strings. So you are comparing "true"!=true which is always true.

If you want to compare the value, you can use like the following. JSON.parse(localStorage.getItem('no_remind_change_pwd')) != true

That means, the following is true

console.log(JSON.parse("true") === true)

Upvotes: 2

Related Questions