0

On click on the submit button in the form is not getting the form field values. Can someone please advise what could be the issue here ? Following are the versions I am using in the project : "axios": "^0.27.2", "cors": "^2.8.5", "express": "^4.18.1", "multer": "^1.4.4", "mysql2": "^2.3.3", "react-hook-form": "^7.31.2", "react-router-dom": "^6.3.0", "react-scripts": "^5.0.1", "react-tweet-embed": "^2.0.0"

//Codesandbox link

https://codesandbox.io/s/affectionate-currying-5gng14?file=/src/App.js

//proxy settings:

"proxy": "http://localhost:8000"

// requestToJoin.js

     const { register, handleSubmit, formState: { errors }} = useForm();
        const [loginData, setLoginData] = useState("");
        const [helperText, setHelperText] = useState('');
        const [isSent, setIsSent] = useState(false);
        const [formRegister, setRegister] = useState({ _id: '', name: '', email: '', mobile: '', photo: '', code: ''});
    
           const onChange = (e) => {
                e.persist();
                setRegister({ ...formRegister, [e.target.name]: e.target.value });
              }
    
     const onSubmit = e => {
                const formData = new FormData();
              
                for(let key in formRegister) {
                  formData.append(key,formRegister[key]);
                }
              
                if (picture) formData.append("photo", picture);
              
                const config = {
                  headers: {
                      'content-type': 'multipart/form-data' 
                  }
                }
                  const fetchData = async () => {
                    try {
                      const res = await axios.put('http://localhost:8000/service/joinrequest', formData, config);
                      console.log("Front End success message:" + res.data.success);
                      if (res.data.success) {
                        setIsSent(true);

                  }
                  else {
                    console.log(res.data.message);
                    setHelperText(res.data.message);
                  }
                } catch (e) {
                  setHelperText(e.response.data.message);
                }
              }
              fetchData();
            }

<form onSubmit={handleSubmit(onSubmit)}  className="myForm" encType="multipart/form-data">
                        <label>Name</label>
                        <input
                            id="name"
                            name="name"
                            type="text"
                            onChange={onChange}
                            {...register("name", { 
                                required: true,
                                maxLength: 30
                            })}
                        />
                        <section>
                        <span className="nameValidationText">
                             {errors.name && errors.name.type === "required" && <span>Name is required !</span>}
                             {errors.name && errors.name.type === "maxLength" && <span>Name should be less than 30 characters !</span>}
                             
                         </span>
                        </section>
                
                        <label>Email</label>
                        <input
                            id="email"
                            name="email"
                            type="email"
                            onChange={onChange}
                            {...register("email", { 
                                required: true,
                                pattern: {
                                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                                    message: "Please enter a valid email !"
                                }
                            })}
                        />
                        <section>
                        <span className="emailValidationText">
                             {errors.email && errors.email.type === "required" && <span>Email is required !</span>}
                             {errors.email && <span>{errors.email.message}</span>}
                         </span>
                        </section>
                        <label>Mobile</label>
                        <input
                            id="mobile"
                            name="mobile"
                            type="number"
                            onChange={onChange}
                            {...register("mobile", { 
                                required: true,
                                valueAsNumber: true,
                                maxLength: 10
                            })}
                        />
                        <section>
                        <span className="nameValidationText">
                             {errors.mobile && errors.mobile.type === "required" && <span>Mobile is required !</span>}
                             {errors.mobile && errors.mobile.type === "maxLength" && <span>Maximum of 10 digits</span>}
                         </span>
                        </section>

                        <label>Code</label>
                        <input
                            id="code"
                            name="code"
                            type="text"
                            onChange={onChange}
                            {...register("code", { 
                                required: true,
                                maxLength: 6,
                                pattern: {
                                    value:/^[0-9a-zA-Z(\-)]$/, // /^[a-zA-Z0-9]$/i, ///^([a-zA-Z0-9]+)$/i
                                    message: "Only alphanumeric characters allowed !"
                                  }
                            })}
                        />
                        <section>
                        <span className="nameValidationText">
                             {errors.code && errors.code.type === "required" && <span>Code is required !</span>}
                             {errors.code && <span>{errors.code.message}</span>}
                             
                         </span>
                        </section>

                         <label>
                            <span className="loginValidationText">{helperText}</span>
                         </label>
                        <section className="col-low">
                        <input type="submit" />
                        </section>  
                    </form>

enter image description here

enter image description here

4
  • Can you show what the contents of formData is prior to you performing the axios request. What shows up in the developer network tools as the body of the API request? Commented May 29, 2022 at 6:27
  • It is not getting the values from the field, while setting the break point, it is not going further after onSubmit. Commented May 29, 2022 at 6:32
  • Screenshot attached Commented May 29, 2022 at 6:33
  • I could see the form data is displaying as null values Commented May 29, 2022 at 6:36

1 Answer 1

0

You just have to move the onChange props after {...register(...)}

I.e.

                    <input
                        id="name"
                        name="name"
                        type="text"
                        {...register("name", { 
                            required: true,
                            maxLength: 30
                        })}
                        onChange={onChange}
                    />

Note. This solution will not work past react-hook-form Version 7.16.0 due to the introduction of an onChange API inside the register function

<input
  type="text"
  {...register('test', {
    onChange: (e) => {},
    onBlur: (e) => {},
  })}
/>

See Source here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, when I changed the onChange to after register it is geting the feld values, but as you suggested onChange API it is not working any more

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.