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 to format error messages as list in React?

I return the following response from Spring Boot API and want to format properly on my React app:

Array(4)
0: {field: 'lastName', message: 'size must be between 3 and 50'}
1: {field: 'username', message: 'size must be between 3 and 20'}
2: {field: 'password', message: 'size must be between 6 and 100'}
3: {field: 'firstName', message: 'size must be between 3 and 50'}

I have the following alert method that displays messages. But I cannot format the message by including all the error messages by type:

const handleSubmit = (event) => {
  event.preventDefault();
  postWithoutAuth("/auth/signup", formValues)
    .then((response) => {
      setAlert("Signed up successfully", "success");
    })
    .catch((error) => {
      error.response.data.errors.foreach(e => {
        setAlert(<li>{e.field + " " + e.message}</li>);
      })
    });
};

Any idea?

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

>Solution :

Three things

  1. you are in JS so <li>{e.field + " " + e.message}</li> needs to be "<li>" + e.field + " " + e.message + "</li>"
  2. you are pumping a lot of alerts in quick succession.
  3. forEach() is case sensitive. You have foreach()

Presuming that error.response.data.errors contains the array in your question, try the following:

.catch((error) => {
  var alertContents = '<ul>';
  error.response.data.errors.forEach(e => {
    alertContents += "<li>" + e.field + " " + e.message + "</li>\n";
  });
    setAlert(alertContents + </ul>);   
});
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