state isn't reflecting change immediately causing me to have to fun onSubmit twice to get the form to submit
If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn 't have a callback pattern
from Link to suggested question
But I'm Honestly confused on how to implement an on Submit into a use effect I'm sorry I'm new to react
const onSubmit = async(data) = > {
setNameError(nameValidation(data.name));
setphoneError(phoneNumberValidation(data.phoneNumber));
setEmailError(emailValidation(data.email));
setMessageError(messageValidation(data.message));
//Here is where I'm getting caught up, in react dev tools the above states are being set to false but below the noErrors Variable is still reading false after all conditions check true the no Errors is still getting the old values for some reason I even used a settimeout method.
let noErrors = (!nameError && !phoneError && !emailError && !messageError);
if (noErrors) {
try {
// const templateParams = {
// name: data.name,
// email: data.email,
// number: data.phoneNumber,
// message: data.message,
// };
// await emailjs.send(
// process.env.REACT_APP_SERVICE_ID,
// process.env.REACT_APP_TEMPLATE_ID,
// templateParams,
// process.env.REACT_APP_USER_ID
// );
reset();
toastifySuccess();
} catch (e) {
console.log(e);
}
}
};
const hasCharacter = /[a-zA-Z]/g;
export const nameValidation = function nameValidation(name) {
if (name.length > 30) {
return 'This field only accepts 30 characters';
}
if (name.length < 5) {
return 'This field requires five characters';
}
if (/\d/.test(name)) {
return ' This field cannot contain numbers';
}
if (!name.includes(' ')) {
return 'This Field Requires A Space';
}
return false;
};
export const phoneNumberValidation = (number) = > {
if (number.length !== 10) {
return 'A Phone Number Must be ten digits';
}
if (hasCharacter.test(number)) {
return 'A Phone Number Shouldnt Contain A Letter';
}
return false;
};
export const emailValidation = (email) = > {
if (email.length > 30) {
return 'This field only accepts 30 characters';
}
if (email.length < 5) {
return 'This field requires five characters';
}
if (!email.includes('@')) {
return 'Email Addresses require @ Symbol';
}
return false;
};
export const messageValidation = (message) = > {
if (message.length > 500) {
return 'This field only accepts 500 characters';
}
if (message.length < 5) {
return 'This field requires five characters';
}
return false;
};