React/Javascript Comparison Operator Not Working - javascript

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.

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)

It's always good practice to use triple comparison operator like === or !==.
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.

Related

How to do Conditionals in Cypress

In my e2e, I need to check if the datatable is populated first before before checkboxes in the table are clicked.
I am able to check the count like so
cy.get('.p-datatable-table').find('tr').its('length').should('be.gte', 0);
unfortunately, the below does not work.
if (cy.get('.p-datatable-table').find('tr').its('length').should('be.gte', 0)) {
cy.get('.select-all-boxes').click();
}
Any suggestions?
You can't use the expression cy.get('.p-datatable-table').find('tr').its('length').should('be.gte', 0) to perform an if check.
The result of that expression is a chainable, so you have to chain it
cy.get('.p-datatable-table').find('tr').its('length')
.then(length => {
if ( length ) {
cy.get('.select-all-boxes').click()
}
})
Not sure what you expect with .should('be.gte', 0) but it does nothing so I dropped it.

How do I shorthand boolean language for writing conditions?

I have a list of variables that I call tags. Each one changes value from true to false depending on the function executed. These 'tags' act as builder pieces for booleans that I'd like to add in other variables. Basically, I'm trying to shorthand the language in order to make complex boolean conditions. Is this code correct for Javascript? The conditions are not passing as I've intended. cleared would read as true while runScreen and runIndicator read as true
Update I shortened the code and made a function to help strengthen the emphasis on the issue. Please see the code below.
Thanks
//builder variables for condition
let testValueA;
let testValueB;
//condition shorthanded inside a variable
const testCondition = !testValueA && testValueB;
// test function for condition
function testCondionValue() {
testValueA=Math.random() > 0.5;
testValueB=Math.random() > 0.5;
console.log("testValueA is", testValueA, "and testValueB is", testValueB);
if (testCondition) {
console.log(" therefore testCondition is true")
}
else {
console.log("therefore testCondition is false")
}
}
This line:
var cleared = (noHover && !runScreen && !runIndicator);
runScreen is true, then !runScreen is false, then cleared is false.

TypeError: if 'false' not working as expected

I'm doing a PWA quiz application using React.js and I've met the following problematic:
I can get questions objects with only one answer, and some with multiple.
In the case there is only one possible answer, I want to force the user to only have one possibility.
To do that, I made the following algorithm:
clickOnChoice = (key) => {
if (this.state && this.state.correctAnswers) {
let newChoices = INITIAL_CHOICES; // {}
if (this.state.multiChoice) {
console.log("this.state.multiChoice:", this.state.multiChoice); // this.state.multiChoice: false ???
newChoices = JSON.parse(JSON.stringify(this.state.choices)); // {answer_b: 1}
}
newChoices[key] = 1 - (newChoices[key] | 0); // {answer_b: 1, answer_a: 1}
this.setState({
choices: newChoices
}, this.updateNextButtonState);
}
}
However the execution seems to ignore the condition if (this.state.multiChoice).
What am I missing?
Maybe I need a cup of coffee... ☕
Anyway, thanks in advance!
It is more than likely you are trying to checking a string of 'false' rather than an actual boolean value.
you can check that the string is the expected boolean if (this.state.multiChoice === 'true') or change the value of the state property to true || false

How to check if a response variable exists and has value

I have the following post which works and getting expected values. I am only able to enter the if block when the value of resp.count is 1 or above. But I want to be able to get into the if block even when the value of resp.count is 0. In other words I am just checking that the variable exists and has value. I am trying not to use something like the following.
if(resp.count !== undefined){}
Is there a better way to achieve this more elegantly? Thanks.
return post(api, { 'Content-Type': 'multipart/form-data' }, data)
.then((resp) => {
// count minimum value will be 0.
// Able to enter the following IF block only when value of count is 1 or above.
if (resp.count) {
// I want to get in here even if value is 0.
}
})
You can safely check if the resp.count is more than or equal to zero
if (resp.count >= 0) {
}
In an event where the count does not exist, it will not satisfy the condition.
console.log(undefined >= 0)
if (rest.count !== undefined) {} is literally saying "if the count key is defined, run the following code"
I'm not sure how you would write that any more legibly.
The below should do it.
return post(api, { 'Content-Type': 'multipart/form-data' }, data)
.then((resp) => {
// Allow zero and up
if (resp.count >= 0) {
// do something...
}
})
For this to walk you'll need to check against falsy values. I think, you'll want to make sure, that the value is neither null, undefined nor "".
For the first two, you could compare against != null (not !== to catch type conversions). If you want to exclude empty string as well, I would follow SamwellTarly's suggestion and compare >= 0.

IF condition using string

I am programming in Polymer 1.0 and am trying to create an IF function to change the value of a property. My function is the following:
_searchButton: function(selectednamedropdown, selectedtypedropdown){
if (selectednamedropdown=="no_name_selected" && selectedtypedropdown=="no_type_selected"){
this.searchUsagesBtn = true
} else{
this.searchUsagesBtn = false
}
}
In my mind when selectednamedropdown is equal to "no_name_selected" and selectedtypedropdown is equal to "no_type_selected" the function should set searchUsagesBtn to true and when they are not these values, false.
However, the function does not ever seem to be returning true even when these conditions are met. Any ideas why this might be? Thanks for all help
When I run your function like this:
let searchUsagesBtn;
function search(selectednamedropdown, selectedtypedropdown) {
if (
selectednamedropdown === "no_name_selected" &&
selectedtypedropdown === "no_type_selected"
) {
searchUsagesBtn = true;
} else {
searchUsagesBtn = false;
}
}
search("no_name_selected", "no_type_selected");
console.log("button: ", searchUsagesBtn);
I get button: true in console log. So maybe your inputs in this function are not a strings.
The issue was around how JavaScript treats properties within functions. The function was storing the new value and old value of the first property and not any values of the second property. The solution involved making 2 functions to test the strings in each property. Thanks for all assistance

Categories

Resources