Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-hook-form: validate field using an API call in the validation

I'm working on the register component of my app (React front-end, Django back-end), and I'm having a little trouble fleshing out all the error handling when validating email addresses. The way I have my users table set up, both the user's email and username must be unique, and I have the uniqueness specified in my Django models, but now I'm working on the error handling in my React components to prevent the API from getting register requests with already used emails/usernames. I have a simple API call for both username and email, that takes the email/username and returns true or false depending on if the value exists in the users table.

The issue I'm having is the validation doesn't seem to be properly listening to the results of the validation's API call. The API call is working correctly, but the validation doesn't seem to change between valid and invalid email addresses.

Here is my function for checking the email's validity:

    const checkEmailExists = (email) => {
    const formData = new FormData();
    formData.append('email', email)
    axiosInstance
        .post('/user/checkemailexists/', formData)
        .then((response) => {
            console.log(response.data.isAvailable);
            return response.data.isAvailable;
        });
    };

And this is the form field for email

                <div>
                <label className="text-gray-600 font-medium block mt-4">Email Address</label>
                <input 
                    className="border-solid border-gray-300 border py-2 px-4 w-full rounded text-gray-700"
                    name="email_address" 
                    type= "email"
                    {...register('email_address', { 
                        required: { value: true, message: "This field is required"}, 
                        validate: {
                            checkEmailExists: (value) => checkEmailExists(value) || "This email address is already in use",
                        }
                    })}
                />
                {errors.email_address && (
                <div className="mb-3 text-normal text-red-500">
                    {errors.email_address.message}
                </div>
                )}
                </div>

At the moment I have the form set to mode: "onSubmit" and reValidateMode: "onSubmit", but I don't think that matters too much for this.

What I ~think~ might be this issue is something to do with the synchronization between the validation happening and the API call that is made for that validation, maybe the validation is coming back before the API call does, so my results are being wonky? I'm not quite skilled enough at the moment to figure this out myself, and there doesn't seem to be too much on this from my searching, so any help would be greatly appreciated!

like image 437
Chowdahhh Avatar asked Sep 16 '26 11:09

Chowdahhh


1 Answers

Double-check your API in the browser console or debugger - response.data.isAvailable === "true" is suspicious, because I would expect response.data.isAvailable === true (or, simplified, return response.data.isAvailable) - in other words, your API should be returning an actual boolean.

Async validation ought to work; see here for an example.

Showing an error message won't work as you expect; checkEmailExists returns a promise, which is truthy (it's a promise, not null/false/undefined), so "This email address is already in use" is never evaluated. Instead, move "This email address is already in use" within your checkEmailExists or a .then block.

like image 126
Josh Kelley Avatar answered Sep 18 '26 02:09

Josh Kelley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!