lukeet
lukeet

Reputation: 491

How to check multiple states in reactjs on an if statement?

There has to be a cleaner way to do this I just can't think of one cause this looks terrible I want to check multiple states in an if statement atm this is the only way I can think to get it to work. I think some form of an array may work but I can't think how to make it in react?

calculate_bmi = () => {
  if (this.state.Gender !== "") {
    if (this.state.Goal !== "") {
      if (this.state.Weight !== "") {
        if (this.state.Height !== "") {
          if (this.state.Age !== "") {
            console.log(
              this.state.Gender,
              this.state.Goal,
              this.state.Weight,
              this.state.Height,
              this.state.Age
            );
          } else {
            alert(
              "Please enter your Height, Weight and Age so we can achieve your goals!"
            );
          }
        } else {
          alert(
            "Please enter your Height, Weight and Age so we can achieve your goals!"
          );
        }
      } else {
        alert(
          "Please enter your Height, Weight and Age so we can achieve your goals!"
        );
      }
    } else {
      alert(
        "Please enter your Height, Weight and Age so we can achieve your goals!"
      );
    }
  } else {
    alert(
      "Please enter your Height, Weight and Age so we can achieve your goals!"
    );
  }
};

Upvotes: 0

Views: 901

Answers (2)

keikai
keikai

Reputation: 15146

A simple way to achieve it.

const check = () => {
  const { Gender, Goal, Weight, Height, Age } = this.state;
  if ([Gender, Goal, Weight, Height, Age].every(x => x !== "")) {
    console.log(list.join('\n'));
  } else {
    alert("Please enter your Height, Weight and Age so we can achieve your goals!");
  }
};

If you need to contain a priority, which was my first thought.

const check = (state) => {
  const checkList = ['Gender', 'Goal', 'Weight', 'Height', 'Age'];
  const isAllGood = !checkList.some(x => {
    const flg = state[x] === '';
    if (flg) {
      alert(`Please enter your ${x} so we can achieve your goals!`);
    }
    return flg;
  });
  if (isAllGood) {
    console.log(state);
  }
}

Upvotes: 1

larz
larz

Reputation: 5766

calculate_bmi = () => {
  if (
    this.state.Gender !== "" &&
    this.state.Goal !== "" &&
    this.state.Weight !== "" &&
    this.state.Height !== "" &&
    this.state.Age !== ""
  ) {
    console.log(
      this.state.Gender,
      this.state.Goal,
      this.state.Weight,
      this.state.Height,
      this.state.Age
    );
  } else {
    alert(
      "Please enter your Height, Weight and Age so we can achieve your goals!"
    );
  }
}  

Upvotes: 1

Related Questions