This is an extension to my previous post: Using useState React hooks and calling other functions
In my code, I have several fields like firstName, lastName, age, gender, city, state, country, etc. So the approach which I am following now is lithe this:
function MyApp() {
const [firstName, setFirstName] = React.useState("");
const [lastName, setLastName] = React.useState("");
const [city, setCity] = React.useState("");
const [gender, setGender] = React.useState("");
const [age, setAge] = React.useState(10);
const [completion, setCompletion] = useState(0);
calculateProgress = (firstName, lastName, city, gender, age) => {
let total = 0;
if(firstName.length >0 ) total += 50;
if(lastName.length >0 ) total += 50;
if(city.length >0 ) total += 50;
if(gender.length >0 ) total += 50;
if(age >0 ) total += 50;
setCompletion(total);
}
return {
<div>
<input id="firstName" onChange={(e) => setFirstName(e.target.value); calculateProgress(e.target.value, lastName, city, gender, age);}
<input id="lastName" onChange={(e) => setLastName(e.target.value); calculateProgress(firstName, e.target.value, city, gender, age);}
<input id="city" onChange={(e) => setCity(e.target.value); calculateProgress(firstName, lastName, e.target.value, gender, age);}
<input id="gender" onChange={(e) => setGender(e.target.value); calculateProgress(firstName, lastName, city, e.target.value, age);}
<input id="age" onChange={(e) => setAge(e.target.value); calculateProgress(firstName, lastName, city, gender, e.target.value);}
</div>
}
}
I want to optimize this code, I have declared so many variables like firstName, lastName, gender and also I have to pass multiple values for each calculateProgress function call. What is the correct way to avoid this.