Why doesnt my react if statement work with "or" - reactjs

I am trying to get a console.log when my newPlan does not equal one of the selected options but it only works without the or statement "||"
Where am I going wrong?
if(newPlan !== "monthlyPlan" || "yearlyPlan"){
console.log("test2")
this.setState({
errorState: "error"
});
}

if(newPlan !== "monthlyPlan" && newPlan !== "yearlyPlan"){
console.log("test2")
this.setState({
errorState: "error"
});
}
EDIT - Explanation:
The && operator only becomes true if all conditions are true. In your case: if newPlan !== "monthlyPlan" is true and newPlan !== "yearlyPlan" is false the whole block becomes false.

Just give condition in both cases,
if(newPlan !== "monthlyPlan" ||newPlan !=="yearlyPlan"){
console.log("test2")
this.setState({
errorState: "error"
});
}

Related

use filter only if an attribute exists with map function

Hello I am using filter with map in react.
props.types.filter(data => (data.is_active === 1)).map((data, index) => {
// some code.
});
I am getting props.types in this component. But sometimes props.types does not contain is_active property. So in that case, map function doesn't return anything. I want to run filter only when data.is_active property exists.
How do I do this ?
UPDATE 1:
As I said above I want to run filter only if is_active is exists but I will always run map.
Add a condition to your filter that checks if is_active is not set.
This way your map will always be executed, except when is_active is not 1.
props.types
.filter((data) => data.is_active === undefined || data.is_active === 1)
.map((data, index) => {
// some code.
});
You can add conditional operator "?" after your filter method.
props.types.filter(data => (data.is_active === 1))?.map((data, index) => {
// some code.
});

How can I setState in componentDidUpdate?

I'm trying to set the state based on API data. 'own' is a field in my API and it contains the Boolean value "true"... I'm storing the data I'm getting from the API in an object called passedXdayPassObj...
I want to set the value of checked property based on the API value of "own"..But it doesn't happen..
Following is my code...
componentDidUpdate(prevProps) {
let passedXdayPassObj;
const { xDayPass } = this.props;
if (xDayPass.xDay && xDayPass.xDayLoading === false && JSON.stringify(xDayPass.xDay) !== JSON.stringify(prevProps.xDayPass.xDay) && !this.props.pathname.includes("createChannel") && !this.state.isSubmit) {
passedXdayPassObj = {
own: xDayPass.xDay.own,
totalCount: xDayPass.xDay.totalCount,
totalValue: xDayPass.xDay.totalValue,
purchaseStart: moment(xDayPass.xDay.purchaseStart).format(),
purchaseEnd: moment(xDayPass.xDay.purchaseEnd).format(),
price: xDayPass.xDay.price,
restricted: false,
utilizeStart: xDayPass.xDay.utilizeStart,
utilizeEnd: xDayPass.xDay.utilizeEnd,
}
if (this.props.location && this.props.location.state && this.props.location.state.view || this.props.location.state.edit) {
this.props.initialize(passedXdayPassObj);
}
if (passedXdayPassObj && passedXdayPassObj.own) {
this.setState({
checked: passedXdayPassObj.own
});
}
}
}
You don't do state updates inside of compoonentDidUpdate() lifecycle methods it results in too many recursions ultimately crashing your app.
Shift the same code inside of componentDidMount() and everything will work fine.

Change value attribute of checkbox base on checked value with knockout JS

I'm trying to a checkbox and send the value YES or NO in my submitted form, base in if is checked or no but the value is not updated
here is my code:
self.checkbox = ko.observable("No");
self.is_checked = ko.computed({
read: function (data) {
return false;
},
write: function (data, event) { self.is_checked() ? self.checkbox('Yes'): self.checkbox('No');}
});
data-bind="checked: is_checked, checkedValue:checkbox"
any clues or links to read, please.
Your computed read function should return true or false so the UI is updated by the checked binding, and you can remove checkedValue entirely (checkedValue usually only makes sense to use with radio elements).
self.checkbox = ko.observable("No");
self.is_checked = ko.pureComputed({
read: () => self.checkbox() === "Yes",
write: (v) => self.checkbox(v ? "Yes" : "No")
})
data-bind="checked: is_checked"

best practise with optional parts on html rendering

I was wondering of a good way to conditionnally render a list of items. Basically I want to render a warning message, if there's a warning, I want to render message to contain a list of all the problems, here is my current approach :
text = (
<div>Orange fields are not mandatory, are you sure you want to submit without :
<ul>
{(() => {
if (e.infos.error === "warning")
return <li>informations</li>
})()}
{(() => {
if (e.links.error === "warning")
return <li>links</li>
})()}
{(() => {
if (e.file.error === "warning")
return <li>file</li>
})()}
</ul>
</div>);
that's ugly, but I wanted to test something, so another approach I took was something like that :
function optionalWarning(props) {
if (props.error === "warning")
return <li>{props.message}</li>;
return null;
}
....
text = (
<div>Orange fields are not mandatory, are you sure you want to submit without :
<ul>
<optionalWarning error="e.infos.error" message="informations" />
<optionalWarning error="e.links.error" message="links" />
<optionalWarning error="e.file.error" message="file" />
</ul>
</div>);
This is prettier, but I don't like the fact that I have to make an external functions to do that, I suppose the best practise is the second one, but are there other ways to do that ?
Use logical operators - the right hand side of these statements will only be used if the left hand side is truthy.
Otherwise, if the left hand side is false, undefined or null, React won't render anything.
<div>Orange fields are not mandatory, are you sure you want to submit without :
<ul>
{e.infos.error === "warning" && <li>informations</li>}
{e.links.error === "warning" && <li>links</li>}
{e.file.error === "warning" && <li>file</li>}
</ul>
</div>
You have to be careful to always ensure a false, undefined or null result when your check fails - e.g. if you're checking the length of a list with {list.length && <Something/>}, when the list is empty this will evaluate to 0 and React will render it as text, whereas a check like {list.length > 0 && <Something/>} will work as you expect.
Use ternary operator for conditional rendering, it will be easy to write conditions inside JSX.
Like this:
<div>Orange fields are not mandatory, are you sure you want to submit without :
<ul>
{e.infos.error === "warning" ? <li>informations</li> : null }
{e.links.error === "warning" ? <li>links</li> : null}
{e.file.error === "warning" ? <li>file</li> : null}
</ul>
</div>
I would go for:
<ul>
{ e.infos.error === "warning" && <li>informations</li> }
{ e.links.error === "warning" && <li>links</li> }
{ e.file.error === "warning" && <li>file</li> }
</ul>

Checking for Undefined In React

I have a scenario where I'm passing data from a reducer into my react state.
data:
{
"id": 1,
"title": "Test",
"content": {
"body": "sdfsdf"
"image": "http://example.com"
}
}
Using componentWillRecieveProps, this works perfectly for retrieving the title.
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps.blog.title,
})
}
However, I'm having difficulty retrieving the nested fields. When I do this:
componentWillReceiveProps(nextProps) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
I get this error:
The error of an undefined body goes away after I click the debugger and the content is loaded. Is there anyway I can combat this issue?
I tried to check for undefined like this:
if (typeof nextProps.blog.content["body"] != 'undefined'){
But this doesn't work either and I believe it's because the blog is undefined.
What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like
componentWillReceiveProps(nextProps) {
if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
}
You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value
In order to check for undefined, you can also use the typeof operator like
typeof nextProps.blog.content != "undefined"
I was face same problem ..... And I got solution by using typeof()
if (typeof(value) !== 'undefined' && value != null) {
console.log('Not Undefined and Not Null')
} else {
console.log('Undefined or Null')
}
You must have to use typeof() to identified undefined
In case you also need to check if nextProps.blog is not undefined ; you can do that in a single if statement, like this:
if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
//
}
And, when an undefined , empty or null value is not expected; you can make it more concise:
if (nextProps.blog && nextProps.blog.content) {
//
}
You can try adding a question mark as below. This worked for me.
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps?.blog?.title,
body: nextProps?.blog?.content
})
}
You can check undefined object using below code.
ReactObject === 'undefined'

Resources