0

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)
    }

})

1 Answer 1

1

You could use the error handler. You are already checking if the user exists. But instead of sending a 201 code, send an error code (400 suggested), which will trigger the error catcher (.catch()) in your frontend. There you can check if the status is 400 through error.response.status and toggle a popup component to display an error message.

Backend:

router.post("/register", async (req, res) => {
const { identity, names, phone, email, city, address, subject, classes, message } = req.body


try {
    const userExists = await User.findOne({ email: email })
    if (userExists) return res.status(400).json({ error: "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 successfully" });        
} catch (err) {
    // Your server error handling...
    console.log(err)
}

Frontend:

 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.status === 400) {
          // This line is for toggling the popup component
          shouldShowErrorMessage(true);
          console.log(error.response.data);
        }
      });
  };
Sign up to request clarification or add additional context in comments.

5 Comments

can you please show how to do it...i have tried but god knows what is coming!!!
@anitaSingh added
showing 'shouldShowErrorMessage' is not defined.
it is a handler function to toggle between error and non error status, you should define it @anitaSingh
as @nima said, its a handler that you should define yourself to hide/show a component. Usually we use useState for it. @anitaSingh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.