Reputation: 842
I have this function that uses validate from yup and it has async function in it. If I want to use the whole function how can I wait for it to finish here is code
const handleSubmit = () => {
companyRef.handleProfileFormSubmit();
setModal(true);
setIsSubmitting(true);
console.log(companyRef.handleFocusOnError());
if (!companyRef.handleFocusOnError() && !isButtonValid) {
console.log('first if in handlesubmut', companyRef.handleFocusOnError());
handleBankDetailsClick();
}
if (isButtonValid && !companyRef.handleFocusOnError()) {
bankRef.handleBankFormSubmit();
history.push(DASHBOARD);
} else if (isButtonValid && companyRef.handleFocusOnError()) {
setIsBankDetailsOpen(true);
}
};
I want to wait for the first sentence to finish which is
companyRef.handleProfileFormSubmit();
the async function is here
handleProfileFormSubmit = () => {
const { profile } = this.state;
const { errorValues } = this.state;
let errorExists = false;
let urls = url.format(profile.website.value);
if (!startsWith(urls, 'http://') && !isEmpty(urls)) {
urls = 'http://' + urls;
}
console.log(urls);
this.schema
.validate(
{
name: profile.name.value,
industry: profile.industry.value,
address: profile.address.value,
crn: profile.crn.value,
website: urls,
employeesNbr: profile.employeesNbr.value,
phoneNumber: profile.phoneNumber.value,
userRole: profile.userRole.value,
personCheck: profile.personCheck.value,
},
{ abortEarly: false },
)
.catch(err => {
errorExists = true;
const errors = {};
for (const i of err.inner) {
errors[i.path] = i.message;
}
const sortedErrors = Object.keys(errors);
sortedErrors.forEach(key => {
profile[key].hasError = true;
profile[key].errorMessage = errors[key];
errorValues.inputErrors.value.push(key);
this.setState({ errorValues });
});
})
.then(() => {
console.log('while submitting', errorValues);
this.handleModalError();
if (errorExists) {
this.props.handleCompanyError();
}
});
};
How can I do this?
Upvotes: 1
Views: 110
Reputation: 55663
You're mixing concerns by putting your validation and submit handler into one, but it's still possible (and fine, extract stuff into functions to make it less complicated).
Below example shows where to handle validation errors and submission errors (if submission is async, which it usually is):
handleProfileFormSubmit = async () => {
try {
await this.schema.validate({...});
// now you know your form is valid - move on to submission
try {
await processSubmission(...);
// submission successful!
} catch(err) {
// error occurred while submitting
}
} catch(err) {
// error occurred while validating
}
};
Upvotes: 2