0

I am performing validation on the server with Node.js and sending the response back to the client

try {
  const response = await register(user);
  console.log(response);
} catch (ex) {
  if (ex.response && ex.response.status === 422) {
    const errors = ex.response.data.errors;
    this.setState({ errors });
  }
}

If I console.log(this.state.errors) I get:

(5) [{…}, {…}, {…}, {…}, {…}]
0: {name: "Name required"}
1: {name: "Name should be more than 3 characters"}
2: {email: "Invalid email address"}
3: {password: "Password required"}
4: {password: "Password should be at least 6 characters"}
length: 5
__proto__: Array(0)

I then want to just loop through all the errors and display them one underneath each other.

     {this.state.errors &&
        this.state.errors.map(error => <li>{error}</li>)}

But I get an error that says:

this.state.errors.map is not a function

1 Answer 1

2

Apparently sometimes ex.response.data.errors isn't an array, probably an object. I would suggest you to not only check if this.state.errors exist, but also to make sure that it's an array.

{Array.isArray(this.state.errors) &&
    this.state.errors.map(error => <li>{error.name}</li>)}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer. When I submit the form after using your code I get this: Error:Objects are not valid as a React child (found: object with keys {name}). If you meant to render a collection of children, use an array instead.
@user10980228 I've edited my answer. Just replace {error} with {error.name}
Thanks, that works for name. But it doesn't list the email and password errors. Is there no way to just use {error} to list ALL errors without out having to do {error.name}, {error.email} and {error.password}
@user10980228 You could e.g. unify errors on the API side so it would return array of strings, not array of objects.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.