I have several values in the frontend and am using useState Hook to update them. All seem to do fine including the Bmi value at least on the front end. But when I post them, all go well except that at the first submit, I get 0 (initial state value of bmi) instead of the computed value.
What am I doing wrong? Please help. Thanks.
Below are some snippets of my code:
const [bmi, setBmi] = useState('0');
const client = axios.create({ baseURL: "https://localhost:8080/patient/addPatient" });
const addPosts = (pName,pAge,pSex,pWeight,pHeight,pBMI) => { client .post('http://localhost:8080/patient/addPatient', { name: pName, age: pAge, sex: pSex, weight: pWeight, height: pHeight, bmi: pBMI }) .then((response) => { setPosts([response.data, ...posts]); });
};
I compute the BMI value like so:
let bmi_val = (weight / (height * height)).toFixed(1);
And compare it for different ranges to give the right message.
let handleClick={
(event) => {
event.preventDefault();
if (weight === 0 || height === 0) {
alert("Enter valid values, please. ")
setImgUrl('');
} else {
// update all the values
setName(name)
setSex(sex)
setAge(age)
setWeight(weight)
setHeight(height)
let bmi_val = (weight / (height * height)).toFixed(1);
// console.log(`bmi is ${bmi}`); // for testing
if (bmi_val <= 18.5) {
setMessage("You are underweight")
setImgUrl(underweight)
setBmi(bmi_val)
} else if (bmi_val > 18.5 && bmi < 24.9) {
setMessage("You have normal weight")
setImgUrl(normalweight)
setBmi(bmi_val)
} else if (bmi_val >= 25.0 && bmi < 29.9) {
setMessage("You are overweight")
setImgUrl(overweight)
setBmi(bmi_val)
} else if(bmi_val >= 30.0){
setMessage("You are obese")
setImgUrl(obese)
setBmi(bmi_val)
}
}
// setBmi(bmi_val);
addPosts(name, age, sex, weight, height, bmi); // posts data to the database
}
}`code here
the handleClick() method is a prop to a child component. In the child I call is to compute the bmi and also give the appropriate message and also post to the db using the addPosts() method.