react-form trouble with api validation | Objects are not valid as a React child

Describe the bug
So, I have an api which is consumed by the react-hook-form at the frontend.
I contact the api for validation and in turn the api returns errors in the form. So What I want to do with those errors is set those errors to the respective form fields.

Codesandbox link (Required)
Include a codesandbox will help us to investigate the issue quicker.

Expected behavior
I expect the error given by the api to be added as a field error

Desktop (please complete the following information):

  • OS: Windows
  • Browser Chrome
  • Version 22

Additional context
The api response format is like this:

error: {
field_name : error_obj
}

This is how I set the errors

export default function RegistrationForm () {
    const { register, handleSubmit, setError, errors } = useForm();
    const onSubmit = data => {
    axios.post('/api/register/', data)
        .then(response =>{
            const token = response.data.token;
            localStorage.setItem('token', token);
            //setJwt(token);
        })
        .catch(error =>{
            const api_errors = error.response.data.error
            for (let field_property in api_errors) {
                console.log(api_errors);
                console.log(api_errors[field_property]);
                console.log(api_errors[field_property][0]);
                setError(field_property, "manual", api_errors[field_property][0]);

            console.log(errors);
            console.log(errors.email);
            }
        });
    }

However, when I try to set the errors like that, I get this error:

Objects are not valid as a React child (found: object with keys {0, 1, 2, 3, 4, 5, ref}). If you meant to render a collection of children, use an array instead.

Why am I getting this error?
This is the actual error object returned by the api:

{email: Array(1), username: Array(1), password: Array(1), last_name: Array(1), first_name: Array(1)}
email: ["This field is required."]
first_name: ["This field is required."]
last_name: ["This field is required."]
password: ["This field is required."]

Any suggestions?
Can someone please help me fix this issue? thanks!

Author: Fantashit

1 thought on “react-form trouble with api validation | Objects are not valid as a React child

  1. fixed!

    this is what was the problem:
    there wasn’t any proper provision to display the errors

    after adding this to each field, it was fixed:

    <h3>Email</h3>{errors.email && <span className="errorMsg">{errors.email.message}</span>}
                    <input name= "email" type="email" className={errors.email ? "errorInput" : "formInput"}
                    ref={register()} />

    thanks a lot @bluebill1049
    and also I saw lots of unanswered questions on the internet regarding this could you mark this as the solution?

Comments are closed.