Home > other >  How can we get the text field value during onChange method in latest react-hooks-form
How can we get the text field value during onChange method in latest react-hooks-form

Time:05-30

How can we get the text field value during onChange method in latest react-hooks-form in version 7.31.2. Now I am getting blank values during on click on Submit button.Could someone please advise me on this.

Here is my CSB link for reference: https://codesandbox.io/s/affectionate-currying-5gng14?file=/src/App.js

const {
  register,
  handleSubmit,
  formState: { errors },
} = useForm();
const [formRegister, setRegister] = useState({ _id: "", name: "", email: "" });

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
      );

      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)} encType="multipart/form-data">
  <label>Name</label>
  <input
    id="name"
    name="name"
    type="text"
    {...register("name", {
      onChange: (e) => {
        // how can we get the value here
      },
      required: true,
      maxLength: 30,
    })}
  />
  <label>Email</label>
  <input
    id="email"
    name="email"
    type="email"
    {...register("email", {
      onChange: (e) => {
        // how can we get the value here ?
      },
      required: true,
      pattern: {
        value: /^[A-Z0-9._% -] @[A-Z0-9.-] \.[A-Z]{2,4}$/i,
        message: "Please enter a valid email !",
      },
    })}
  />
</form>;

CodePudding user response:

In the registered onChange(e), e is a synthetic event which contains a property nativeEvent which has a path property pointing to the native element.

{...register("name", {
  onChange: (e) => {
    const val = e.nativeEvent.path[0].value;

    // you can update formRegister here, 
    // but note it updates on every character
    setRegister(previous => ({
      ...previous, 
      name: val
    }))


On clicking the Submit button

The data from the form is passed into the onSubmit() callback

const onSubmit = (e) => {
    const formData = new FormData();

    console.log(e.name);  // whatever was typed into the name field

    for (let key in e) {
      formData.append(key, e[key]);
    }

CodePudding user response:

You can use watch from react-hook-form API to get the changes in the text of input field. Can you elaborate your goal why you wanna do it. This may help understand if we can use watch or not and if overriding onChange is the only solution to achieve it?

  • Related