I have an if condition which will change the state value, and the else part assigns a different value to the state. but both are being executed. how to avoid that.
getJobId = (event) => {
const { appliedjobs } = this.props
{appliedjobs && appliedjobs.map(job => {
if(event.target.getAttribute('name')===job.id)
{
this.setState({applystatus:job.applystatus},()=>{
console.log('====================================');
console.log(this.state.applystatus);
console.log('====================================');
})
}
else if(event.target.getAttribute('name')!=job.id){
this.setState({applystatus:"apply now"},()=>{
console.log('====================================');
console.log("else ",this.state.applystatus);
console.log('====================================');
})
}
})}
this.setState({
jobid: event.target.getAttribute('name')
}, () => this.sendJobId())
}
Your else if
statement might return the same, as !=
can return a false positive. You just need an else statement though:
if(event.target.getAttribute('name')===job.id) { ... }
else { ... }
This should in any way only execute the setState
function within the else block if the if
statement is definitely false.
You are mapping over your applidjobs
array, and you set state.applystatus
in both branches of your if
statement during each iteration. So the applystatus
value will be the one set during the last iteration:
appliedjobs.map(job => {
if (event.target.getAttribute('name') === job.id) {
this.setState({ applystatus: job.applystatus })
} else if (event.target.getAttribute('name') != job.id) {
this.setState({ applystatus: 'apply now' })
}
})
this.setState({ jobid: event.target.getAttribute('name') }, () => this.sendJobId())
I suggest to look for the job matching the name
attribute, if found, set the applystatus
to the job's status, else set it to apply now
, you don't need to map or use an if/else
statement:
const jobid = event.target.getAttribute('name');
const job = appliedjobs.find(({ id }) => id === jobid );
this.setState({
applystatus: job ? job.applystatus : 'apply now,
jobid
}, () => this.sendJobId());
If I understood your code, you should be doing something like this:
getJobId = (event) => {
const { appliedjobs } = this.props
const jobid = event.target.getAttribute('name')
const job = appliedjobs.find( j => j.id == jobid)
const applystatus = job ? job.applystatus : "apply now"
this.setState({ applystatus, jobid })
}
Finding the job per its id and setting on state its status, is that correct?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.