Andrew Kim Andrew Kim - 2 months ago 14
Javascript Question

How can i use the return value of a function to be the return value of another function

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.

Answer

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.

Comments