I have a array of object
const formFields = { firstName: { value: '', label: 'FirstName', type: 'text', placeHolder: 'Enter Firstname', helperText: '', required: false, error: false }, lastName: { value: '', label: 'LastName', type: 'text', placeHolder: 'Enter LastName', helperText: '', required: false, error: false }, emailID: { value: 'sfas', label: 'emailID', type: 'email', placeHolder: 'Enter Email ID', helperText: '', required: true, error: false }, password: { value: '', label: 'password', type: 'password', placeHolder: 'Enter password', helperText: '', required: true, error: false }, confirmPassword: { value: '', label: 'confirmPassword', type: 'password', placeHolder: 'Enter Confirm Password', helperText: '', required: true, error: false } } const [inpValues, setInpValues] = useState(formFields)
Filter and Update
I am trying to filter the object by values where required === true
and value.length === 0
and update the filtered array values like helperText = "Enter the " + label
and error = true
const validate = () => { const requiredFields = Object.values(inpValues).filter((fields) => { if (fields.required === true && fields.value.length === 0) { //How to setInpValues //setInpValues(...inpValues, fields: { fields.helperText = "Enter the " + fields.label}) //fields.error = true } }) } <MyButton color="primary" handleOnClick={validate} text="SIGN UP"></MyButton>
Advertisement
Answer
The validate function should be, this will also take care of reverting the error back in case of validity.
const validate = () => { let newValues={...inpValues} const requiredFields = Object.keys(newValues).forEach((key) => { let field=newValues[key]; if (field.required === true && field.value.length === 0) { field.helperText=`Enter the ${field.label}`; field.error = true; newValues[key]= field; }else{ newValues[key].error=false; newValues[key].helperText=''; } }) setInpValues(newValues); }