</> setValues: (value: Partial<TFieldValues> | ((data: TFieldValues) => Partial<TFieldValues>), options?: SetValueConfig) => void
This function allows you to dynamically set multiple field values at once and have the options to validate and update the form state. It also accepts a callback function that receives the current form values, making it easy to derive the next state from the existing one.
Props
| Name | Description | |
|---|---|---|
valuePartial<TFieldValues> | (data: TFieldValues) => Partial<TFieldValues> | An object containing the field values to update, or a callback function that receives the current form values and returns the updated values. This argument is required. | |
options | shouldValidateboolean |
|
shouldDirtyboolean |
| |
shouldTouchboolean | Whether to set the updated inputs to be touched. |
RULES
-
When using the callback form, the function receives a snapshot of the current form values and should return only the fields you want to update.
-
This method does not reset the form. Use
resetif you need to reinitializedefaultValues.
Examples
Basic
import { useForm } from "react-hook-form"const App = () => {const { register, setValues } = useForm({defaultValues: {firstName: "",lastName: "",},})return (<form><input {...register("firstName")} /><input {...register("lastName")} /><buttontype="button"onClick={() => setValues({ firstName: "Bill", lastName: "Luo" })}>setValues</button></form>)}
Callback (derive next state from current values)
import { useForm } from "react-hook-form"const App = () => {const { register, setValues } = useForm({defaultValues: {name: "",count: 0,},})return (<form><input {...register("name")} /><input type="number" {...register("count")} /><buttontype="button"onClick={() => {setValues((data) => {return {...data,name: "test",}})}}>setValues with callback</button></form>)}
With options
import { useForm } from "react-hook-form"const App = () => {const { register, setValues } = useForm({defaultValues: {firstName: "",lastName: "",},})return (<form><input {...register("firstName", { required: true })} /><input {...register("lastName", { required: true })} /><buttontype="button"onClick={() =>setValues({ firstName: "Bill", lastName: "Luo" },{ shouldValidate: true, shouldDirty: true, shouldTouch: true })}>setValues with validation</button></form>)}
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.