Reputation: 1316
I am using useSatate for managing my form errors:
const [formErrorObj, updateForErrormObj] = useState({
name_error: '',
email_error: '',
contact_number_error: '',
username_error: '',
password_error: '',
promo_mail_error: ''
})
and this is where I am creating object with all form errors:
function onSubmitHandler(event) {
event.preventDefault();
const error = validate();
if (error) {
const errorList = error.error.details;
const newErrorObj = {};
for (let err in errorList) {
newErrorObj[error.error.details[err].context.key + '_error'] = error.error.details[err].message
}
updateForErrormObj({ ...formErrorObj, ...newErrorObj })
console.log(newErrorObj, formErrorObj)
}
}
Newly created object looks something like this :
contact_number_error: ""Contact Number" is not allowed to be empty"
email_error: ""Email" must be a valid email"
name_error: ""Username" is not allowed to be empty"
password_error: ""Password" length must be at least 5 characters long"
username_error: ""Username" is not allowed to be empty"
__proto__: Object
After validation when I try to update state using :
updateForErrormObj({ newErrorObj }) // try 1
updateForErrormObj(newErrorObj) // try 2
updateForErrormObj({ ...formErrorObj, ...newErrorObj }) // try 3
no try from three works form me. I am not sure what I am doing wrong here.
Upvotes: 0
Views: 124
Reputation: 254
If you mean by it does not update because you console.log it. It is how it works, it is async. You can check it by console.log in the useEffect
, so you can see it actually does update.
Upvotes: 1