I'm working on small react project where trainer used below code
created states using useState hooks
const [purchasePrice, setPurchasePrice] = useState("");
const [downPayment, setDownPayment] = useState("");
const [loanTerm, setLoanTerm] = useState("");
const [loanApr, setLoanApr] = useState("");
const [monthlyPayments, setMonthlyPayments] = useState(0.0);
Then passed those to afunction which returns true or false and also updates the state
//Validate fields
const validatedPrice = await validateField(purchasePrice, setPurchasePrice);
const validatedPayment = await validateField(downPayment, setDownPayment);
const validatedLoanTerm = await validateField(loanTerm, setLoanTerm);
const validatedApr = await validateField(loanApr, setLoanApr);
code for validation :
const validateField = (field, setvalue) => {
let int = parseFloat(field);
if(field === "" || field === 0) {
setvalue({...field.values, error: "Please enter a value"});
return false;
} else if(isNaN(int)) {
setvalue({...field.values, error: "Please enter a number"});
return false;
} else {
setvalue(int);
return true;
}
};
in the validation function how did he add the object type to the state while the state initial type was string. 1.Can we change the type of useState initial value at runtime ? 2.what is .values in the line
setvalue({...field.values, error: "Please enter a value"});
is it a property/function of object.
Please find the full code here if you need full code to understand