Setting React state within handleSubmit callback using react-hook-form

I’m building some user inputs for a client-side application with react-hook-form.

Users should be able to update an input. Then onBlur, react-hook-form is to validate the input and update an react useState object. If validation fails, the external state is not updated.

The following code fails to keep the external state object up to date onBlur.

As the handleSubmit() function is async, i’m unable to set the state.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function App() {
const [value, setValue] = useState({
name: "",
});
const { register, handleSubmit } = useForm({ mode: "onBlur" });
return (
<>
{errors?.name ? <p>{errors.name.message}</p> : null}
<label htmlFor="name">Name</label>
<input
{...register("name", {
onBlur: handleSubmit((data) => {
setValue((prev) => ({ ...prev, name: data.name }));
}),
minLength: { value: 2, message: "Name is too short" },
required: { value: true, message: "Name is required" },
})}
id="name"
type="text"
/>
</>
);
}
</code>
<code>function App() { const [value, setValue] = useState({ name: "", }); const { register, handleSubmit } = useForm({ mode: "onBlur" }); return ( <> {errors?.name ? <p>{errors.name.message}</p> : null} <label htmlFor="name">Name</label> <input {...register("name", { onBlur: handleSubmit((data) => { setValue((prev) => ({ ...prev, name: data.name })); }), minLength: { value: 2, message: "Name is too short" }, required: { value: true, message: "Name is required" }, })} id="name" type="text" /> </> ); } </code>
function App() {
  const [value, setValue] = useState({
    name: "",
  });

  const { register, handleSubmit } = useForm({ mode: "onBlur" });

  return (
    <>
      {errors?.name ? <p>{errors.name.message}</p> : null}
      <label htmlFor="name">Name</label>
      <input
        {...register("name", {
          onBlur: handleSubmit((data) => {
            setValue((prev) => ({ ...prev, name: data.name }));
          }),
          minLength: { value: 2, message: "Name is too short" },
          required: { value: true, message: "Name is required" },
        })}
        id="name"
        type="text"
      />
    </>
  );
}
  • I’ve tried wrapping handleSubmit in async / await – however this doesn’t yield anything as the handleSubmit method will only expose the result to the callback function.
  • useEffect on the react-hook-form watch() function; issue with this is you dont get the validation.
  • Creating my own synchronous methods to validate seem to defeat the purpose of using react-hook-form.

New contributor

user28682631 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

updated code — this will work for you.. i have updated the code.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useState } from "react";
import { useForm } from "react-hook-form";
function App() {
const [value, setValue] = useState({
name: "",
});
const {
register,
trigger,
getValues,
formState: { errors },
} = useForm({ mode: "onBlur" });
const handleBlur = async (fieldName) => {
const isValid = await trigger(fieldName); // Validate the field
if (isValid) {
const fieldValue = getValues(fieldName); // Get the current field value
setValue((prev) => ({ ...prev, [fieldName]: fieldValue }));
}
};
return (
<>
{errors?.name && <p>{errors.name.message}</p>}
<label htmlFor="name">Name</label>
<input
{...register("name", {
onBlur: () => handleBlur("name"), // Call the custom blur handler
minLength: { value: 2, message: "Name is too short" },
required: { value: true, message: "Name is required" },
})}
id="name"
type="text"
/>
</>
);
}
export default App;
</code>
<code>import React, { useState } from "react"; import { useForm } from "react-hook-form"; function App() { const [value, setValue] = useState({ name: "", }); const { register, trigger, getValues, formState: { errors }, } = useForm({ mode: "onBlur" }); const handleBlur = async (fieldName) => { const isValid = await trigger(fieldName); // Validate the field if (isValid) { const fieldValue = getValues(fieldName); // Get the current field value setValue((prev) => ({ ...prev, [fieldName]: fieldValue })); } }; return ( <> {errors?.name && <p>{errors.name.message}</p>} <label htmlFor="name">Name</label> <input {...register("name", { onBlur: () => handleBlur("name"), // Call the custom blur handler minLength: { value: 2, message: "Name is too short" }, required: { value: true, message: "Name is required" }, })} id="name" type="text" /> </> ); } export default App; </code>
import React, { useState } from "react";
import { useForm } from "react-hook-form";

function App() {
  const [value, setValue] = useState({
    name: "",
  });

  const {
    register,
    trigger,
    getValues,
    formState: { errors },
  } = useForm({ mode: "onBlur" });

  const handleBlur = async (fieldName) => {
    const isValid = await trigger(fieldName); // Validate the field
    if (isValid) {
      const fieldValue = getValues(fieldName); // Get the current field value
      setValue((prev) => ({ ...prev, [fieldName]: fieldValue }));
    }
  };

  return (
    <>
      {errors?.name && <p>{errors.name.message}</p>}
      <label htmlFor="name">Name</label>
      <input
        {...register("name", {
          onBlur: () => handleBlur("name"), // Call the custom blur handler
          minLength: { value: 2, message: "Name is too short" },
          required: { value: true, message: "Name is required" },
        })}
        id="name"
        type="text"
      />
    </>
  );
}


export default App;

New contributor

Shivam Tiwari is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật