I have a MERN project. I have a form data. i want to insert in my database. Data is successfully inserted but I want to check duplicate email from my database and show error on reactjs page(like react toastify)
basically i want to show some error to user
so how to fetch email from backend and show some result in reactjs.
As there are some same questions but it would't help me
So please give me some suggestions how can i do it?
register.js
const Register = () => {
const [newUser, setNewUser] = useState({
identity: "",
names: "",
phone: "",
email: "",
city: "",
address: "",
subject: "",
classes: "",
message: "",
});
const handleSubmit = (e) => {
e.preventDefault();
axios({
method: "post",
url: "/register",
data: JSON.stringify(newUser),
headers: { "Content-Type": "application/json" },
}).then((response) => {
toast.dark(`${newUser.names} 🤵 registered Sucessfully `, {
position: "top-center",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
})
.then((data) => {
console.log(data);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
}
});
};
const handleChange = (e) => {
setNewUser({ ...newUser, [e.target.name]: e.target.value });
};
router.post("/register", async (req, res) => { const { identity, names, phone, email, city, address, subject, classes, message } = req.body
// if (!identity || !names || !phone || !email || !city || !address || !subject || !classes || !message) {
// return res.status(422).json({ error: "Please mark all the field" })
// }
try {
const userExit = await User.findOne({ email: email })
if (userExit) {
// res.status(422).json({ error: "Email already exit" })
alert("email already exit")
}
// else if (password != cpassword) {
// return res.status(422).json({ error: "password and confirm password don not match" })
// }
const user = new User({identity ,names, phone,email,city,address, subject, classes, message })
await user.save()
res.status(201).json({ message: "user registered successfulluy" })
} catch (err) {
console.log(err)
}
})
auth.js
router.post("/register", async (req, res) => {
const { identity, names, phone, email, city, address, subject, classes, message } = req.body
try {
const userExit = await User.findOne({ email: email })
if (userExit) {
// res.status(422).json({ error: "Email already exit" })
alert("email already exit")
const user = new User({identity ,names, phone,email,city,address, subject, classes, message })
await user.save()
res.status(201).json({ message: "user registered successfulluy" })
} catch (err) {
console.log(err)
}
})