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?
>Solution :
Three things
- you are in JS so
<li>{e.field + " " + e.message}</li>needs to be"<li>" + e.field + " " + e.message + "</li>" - you are pumping a lot of alerts in quick succession.
forEach()is case sensitive. You haveforeach()
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>);
});