e.T55
e.T55

Reputation: 465

handling error msg from express display on react

how can set an error message to display on react when a button is clicked.the Button is getting created dynamically I am sending status I went through many answers but nothing is working for me how can display the custom messages in react

express

router.post("/registerClass", (req, res) => {
  // const courseID = req.body.courseID
  // const studentID = req.body.studentID
  console.log(req.body.courseID);

  Registration.findOne({
    $and: [
      {
        courseID: req.body.courseID
      },
      {
        studentID: req.body.studentID
      }
    ]
  })
    .exec()
    .then(reg => {
      if (reg) {
        return res.status(400).json({
          err: "Already Registered for this class"
        });
      } else {
        const registration = new Registration({
          _id: new mongoose.Types.ObjectId(),
          courseID: req.body.courseID,
          studentID: req.body.studentID
        });
        registration.save().then(result => {
          res.status(201).json({
            Msg: "Succesfully Register"
          });
        });
      }
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        err: err
      });
    });
});

react

registerClass = e => {
this.setState({
  courseID: e.target.value
});
e.preventDefault();
var data = {
  studentID: this.state.studentID,
  courseID: this.state.courseID
};
axios.post("users/registerClass", data).then(res => {
  if (res.status === 201) {
    console.log(res.status);
  }
  console.log(res.data.errors);
});
// .catch(err => {
//   console.log(err);
// });

};

Upvotes: 1

Views: 1504

Answers (1)

Anuj Ladia
Anuj Ladia

Reputation: 184

If I got your question right then this might answer it.

Simplest Option You can simply call window alert dialog to show the error.

window.alert(res.data.errors);

The second option you can use react-toastify npm library or any of the similar libraries available out there, to show the error or any kind of alert on your webpage.

The third option is to create your own Snackbar type Component which is a dialog box which pops in whenever called. You can then, make that component visible every time you get an error on the client side. If you face any issue with this one I can help you with the code.

Hope so this was able to answer your question.

Upvotes: 2

Related Questions