i don't know what is wrong with my code , i check the value with console.log and it gets the value normally but when i submit the form it gets back to undefined , and when i try to check the form with if statement if just send the mail with empty values and sometimes it send undefined
const [mails, setMails] = useState({
userFullName: '',
userEmail: '',
userSubject: '',
userMessage: '',
mailFail : false,
});
const [mailStatues, setMailStatues] = useState(false);
const [mailLoader, setMailloader] = useState(false);
const { userFullName, userEmail, userSubject, userMessage, mailFail } = mails;
const handleChange = e => {
setMails({ ...mails, [e.target.name] : e.target.value})
}
function setFail() {
setMails({ mailFail: true })
setTimeout(() => {
setMails({ mailFail: false })
}, 3000);
}
const handleEmail = async (e) => {
e.preventDefault();
console.log(userFullName , userEmail, userSubject, userMessage)
if ( userFullName ) {
setFail()
}
else {
setMailloader(true);
await axios.post('http://localhost:8000/api/form', {
...mails
},
setMails({
userFullName: '',
userEmail: '',
userSubject: '',
userMessage: '',
})
,
setMailloader(false)
,
setMailStatues(true)
)
}
}
here is the form
<form onSubmit={handleEmail}>
<Input id='inputName' type="text" name="userFullName" label="Name" value={userFullName} change={handleChange} />
<Input id='inputEmail' type="email" name="userEmail" label="Email" value={userEmail} change={handleChange}/>
<Input id='inputSubject' type="text" name="userSubject" label="Subject" value={userSubject} change={handleChange}/>
<TextArea id='inputMessage' type="text" name="userMessage" label="Message" value={userMessage} change={handleChange}/>
<BtnAni string="Submit" loading={mailLoader}/>
</form>
CodePudding user response:
Change these lines
setMails({ mailFail: true })
setTimeout(() => {
setMails({ mailFail: false })
}, 3000);
to
setMails(prev => ({ ...prev, mailFail: true }))
setTimeout(() => {
setMails(prev => ({ ...prev, mailFail: false }))
}, 3000);