Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I pass success or error message using react-toastify when using axios method

I want to show success or error message depending upon the HTTP response status code that I will receiving upon sending my axios request ,using react-toastify (For example if the status code is 406 react-toastify should show a error message like "Some fields are empty" or if status code is "422" is should show a error message like "email already registered" and in case of status code "200" react-toastify should show a message "Account created successfully") on frontend.

Here is my backend api code

router.route('/register').post(upload.single('photo'), (req, res) => {

  const name = req.body.name;
  const email = req.body.email;
  const phone = req.body.phone;
  const work = req.body.work;
  const password = req.body.password;
  const cpassword = req.body.cpassword;
  const photo =  req.file.filename;

  
  if(!name || !email || !phone || !work || !password || !cpassword || !photo ){
    return res.status(406).json({message:"Some fields are missing"}) ;
    
}
  User.findOne({email: email})
  .then((userExist)=>{
         if (userExist){
             return res.status(422).json({Error:"Email already registered"});
            
       }

       const newUserData = {
        name,
        email,
        phone,
        work,
        password,
        cpassword,
        photo
    }

    const newUser = new User(newUserData);
       newUser.save().then(()=>{
        res.status(201).json({message:"user created successfuly"});
        alert("user created succcessfully")
             }).catch((err)=>res.status(500).json({error:"registeration failed"})
             );
         }).catch((err)=>{console.log(err);});
         
         });

Here is the function on front that fetch data from input field

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   const handleSubmit = (e) => {
        e.preventDefault();
        let url = 'http://localhost:3000/register'
        const formData = new FormData();
        formData.append('name', newUser.name);
        formData.append('email', newUser.email);
        formData.append('phone', newUser.phone);
        formData.append('work', newUser.work);
        formData.append('password', newUser.password);
        formData.append('cpassword', newUser.cpassword);
        formData.append('photo', newUser.photo);

        axios.post(url , formData)
             .then(res => {
                console.log(res)
                history.push('/login')
                
             } )
             .catch(err => {
                console.log(err);
                
             });
    }

>Solution :

Assuming you already have react-toastify setup, just check the response status and trigger toast if it’s equal to the value you want, 200 in your case. Like this:

 axios.post(url , formData)
     .then(res => {
        if (res.status === 200)
          toast.success("Success!");

        history.push('/login')
                
        } )
     .catch(err => {
        console.log(err);
                
     });

Edit: If it’s the newUser function you are calling, the status on POST requests will be 201 when they succeed, opposed to 200, which you mentioned in the question. If that’s the case, just replace 200 with 201.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading