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>
CodePudding user response:
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);
}
CodePudding user response:
The array filter callback function expects you to return a boolean that says if the current value should be filtered out or not. I think something like
const validate = () => {
const requiredFields = Object.values(inpValues).filter((fields) => {
if (fields.required === true && fields.value.length === 0) {
return true;
}
return false;
})
setInpValues(requiredFields)
}
this would solve it. In this example you first filter the input values and when they're filtered, you set them to the state. This sets inputValues
to be all the required fields, every time you click.