Greeting i am trying to build instagram clone on the register page i need to check if email is available before we submit register form this is the api controller for checking email
checkEmailAvailability: async (req, res) => {
try {
const email = req.body.email
console.log(email)
const user_email = await User.findOne({ email })
if (user_email) return res.status(409).json({ msg: 'Email Already Taken', success: false })
res.status(200).json({ msg: 'email available', success: true })
} catch (err) {
return res.status(500).json({ msg: err.message, success: false })
}
}
in front end i have an input for email first i check if email input is not empty and not focused then we check if email is valid only then i send request to server to check if available
import { useState, useEffect } from 'react'
import { isEmpty, isEmail } from './InputValidation'
import axios from 'axios'
function Register() {
const [email, setEmail] = useState('')
const [emptyEmail, setEmptyEmail] = useState(true)
const [emailFocused, setEmailFocused] = useState(false)
const onFocus = () => setEmailFocused(true)
const onBlur = () => setEmailFocused(false)
const [validEmail, setValidEmail] = useState(false)
useEffect(() => {
if (isEmpty(email)) {
setEmptyEmail(true)
console.log('email empty')
} else {
setEmptyEmail(false)
console.log('email not empty')
if (!emailFocused) {
console.log('email not focused')
if (isEmail(email)) {
async function checkEmail() {
console.log('checking availability')
const response = await axios.post('http://localhost:8000/checkEmailAvailability', {
email: email
})
if (response.data.success) {
console.log('email available')
setValidEmail(true)
console.log(validEmail)
} else {
console.log('email not available')
setValidEmail(false)
console.log(validEmail)
}
}
checkEmail()
}
}
}
}, [emailFocused, email])
return (
<div className='flex justify-center items-start box-content mb-1 flex-col relative'>
<input
autoComplete='off'
onFocus={onFocus} onBlur={onBlur}
value={email}
onChange={(e) => setEmail(e.target.value)}
type="text"
className=" peer block border border-gray-300 text-xs box-content w-button-w px-2 h-4 pt-9px pb-7px placeholder-transparent"
name="email"
placeholder="Email" />
<label for='email' className={(!emptyEmail) ? 'absolute top-0 left-2 text-xs text-gray-400' : ' absolute top-1 left-2 text-base m-0 text-gray-400'}> Email</label>
</div>
)
}
export default Register
when i enter first email the effect take place and i get response if email valid and availble i get true if not false but when i change email the value of validEmail won't update only update when i select input and deselecte it twice setValidEmail update the value of validEmail only when i trigger it once