Reputation: 3335
I could be wording this a bit weird. Let me lay out some code to help explain. I'm writing a simple react component. This react component has a form where I submit a form. This is what I have so far:
onSubmit(event){
event.preventDefault()
if (this.checkQuantity()){
// this is what i want to be simpler, the return value i want is already in the checkQuantity function in the if condition
return true
} else {
let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)
}
}
checkQuantity(){
if (this.state.quantity > this.props.item.quantity){
alert("Can't buy what's not there!")
return true
} else {
return false
}
}
Like the comment states above, I just want the execution of the form submission to stop. I guess, I'm just looking for best practice in this type of situation. One where I'd like to abstract functionality but use the return value of that abstracted functionality in a conditional as a return.
Upvotes: 0
Views: 65
Reputation: 664528
I'd write
onSubmit(event) {
event.preventDefault()
if (!this.checkQuantity()) {
let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)
}
}
checkQuantity() {
const isToomuch = this.state.quantity > this.props.item.quantity;
if (isToomuch) {
alert("Can't buy what's not there!")
}
return isToomuch
}
Or maybe you want to put the alert
inside the onSubmit
method, then checkQuantity
becomes even simpler. Also you might want to rename checkQuantity
to something more descriptive, like isInvalidQuantity
.
Upvotes: 3
Reputation: 1269
I feel that you are splitting functions unnecessarily. Wouldn't the following code be enough?
onSubmit(event){
event.preventDefault()
if (this.state.quantity > this.props.item.quantity){
alert("Can't buy what's not there!")
} else {
let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)
}
}
Also, like others mentioned, the return value has not significance in your example because you are not checking it.
Upvotes: 0
Reputation: 653
The problem here is you don't just want to return the value of checkQauntity(), you want to act on the return value and then decide what to do. In this case, the code you have is as good as any way of doing it.
But for a more general case (where you are not just returning true or false, you could do something like the following:
onSubmit(event){
event.preventDefault();
var check = checkQuantity();
if (check > 6 ){
return check;
}
else {
//do something else..
}
}
checkQuantity(){
var someNumber = ...someNumber;
return someNumber;
}
Upvotes: 0
Reputation: 133
onSubmit(event){
event.preventDefault()
return checkQuantity();
}
checkQuantity(){
if (this.state.quantity > this.props.item.quantity){
alert("Can't buy what's not there!")
return true
} else {
let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)
return false
}
}
Upvotes: 0