|
| 1 | +--- |
| 2 | +title: setValue |
| 3 | +description: Update field value |
| 4 | +sidebar: apiLinks |
| 5 | +--- |
| 6 | + |
| 7 | +## \</> `setValue:` <TypeText>(name: string, value: unknown, config?: SetValueConfig) => void</TypeText> |
| 8 | + |
| 9 | +This function allows you to dynamically set the value of a <strong>registered</strong> field and have the options to validate and update the form state. At the same time, it tries to avoid unnecessary rerender. |
| 10 | + |
| 11 | +### Props |
| 12 | + |
| 13 | +--- |
| 14 | + |
| 15 | +| Name | | Description | |
| 16 | +| ---------------------------------------- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |
| 17 | +| `name`<br/><TypeText>string</TypeText> | | Target a single field or field array by name. | |
| 18 | +| `value`<br/><TypeText>unknown</TypeText> | | The value for the field. This argument is required and can not be `undefined`. | |
| 19 | +| `options` | `shouldValidate`<br/><TypeText>boolean</TypeText> | <ul><li>Whether to compute if your input is valid or not (subscribed to <TypeText>errors</TypeText>).</li><li>Whether to compute if your entire form is valid or not (subscribed to <TypeText>isValid</TypeText>).</li>This option will update `touchedFields` at the specified field level not the entire form touched fields.</ul> | |
| 20 | +| | `shouldDirty`<br/><TypeText>boolean</TypeText> | <ul><li>Whether to compute if your input is dirty or not against your `defaultValues` (subscribed to <TypeText>dirtyFields</TypeText>).</li><li>Whether to compute if your entire form is dirty or not against your `defaultValues` (subscribed to <TypeText>isDirty</TypeText>).</li><li>This option will update `dirtyFields` at the specified field level not the entire form dirty fields.</li></ul> | |
| 21 | +| | `shouldTouch`<br/><TypeText>boolean</TypeText> | Whether to set the input itself to be touched. | |
| 22 | + |
| 23 | +<Admonition type="important" title="Rules"> |
| 24 | + |
| 25 | +- You can use methods such as [replace](/docs/usefieldarray#replace) or [update](/docs/usefieldarray#update) for field array, however, they will cause the component to unmount and remount for the targeted field array. |
| 26 | + |
| 27 | + ```javascript |
| 28 | + const { update } = useFieldArray({ name: "array" }) |
| 29 | + |
| 30 | + // unmount fields and remount with updated value |
| 31 | + update(0, { test: "1", test1: "2" }) |
| 32 | + |
| 33 | + // will directly update input value |
| 34 | + setValue("array.0.test1", "1") |
| 35 | + setValue("array.0.test2", "2") |
| 36 | + ``` |
| 37 | + |
| 38 | +- The method will not create a new field when targeting a non-existing field. |
| 39 | + |
| 40 | + ```javascript |
| 41 | + const { replace } = useFieldArray({ name: "test" }) |
| 42 | + |
| 43 | + // ❌ doesn't create new input |
| 44 | + setValue("test.101.data") |
| 45 | + |
| 46 | + // ✅ work on refresh entire field array |
| 47 | + replace([{ data: "test" }]) |
| 48 | + ``` |
| 49 | + |
| 50 | +- Only the following conditions will trigger a re-render: |
| 51 | + |
| 52 | + - When an error is triggered or corrected by a value update. |
| 53 | + - When `setValue` cause state update, such as dirty and touched. |
| 54 | + |
| 55 | +- It's recommended to target the field's name rather than make the second argument a nested object. |
| 56 | + |
| 57 | + ```javascript |
| 58 | + setValue("yourDetails.firstName", "value") // ✅ performant |
| 59 | + setValue("yourDetails", { firstName: "value" }) ❌ // less performant |
| 60 | + |
| 61 | + register("nestedValue", { value: { test: "data" } }) // register a nested value input |
| 62 | + setValue("nestedValue.test", "updatedData") // ❌ failed to find the relevant field |
| 63 | + setValue("nestedValue", { test: "updatedData" }) // ✅ setValue find input and update |
| 64 | + ``` |
| 65 | + |
| 66 | +- It's recommended to register the input's name before invoking `setValue`. To update the entire `FieldArray`, make sure the `useFieldArray` hook is being executed first. |
| 67 | + |
| 68 | + **Important:** use `replace` from `useFieldArray` instead, update entire field array with `setValue` will be removed in the next major version. |
| 69 | + |
| 70 | + ```javascript |
| 71 | + // you can update an entire Field Array, |
| 72 | + setValue("fieldArray", [{ test: "1" }, { test: "2" }]) // ✅ |
| 73 | + |
| 74 | + // you can setValue to a unregistered input |
| 75 | + setValue("notRegisteredInput", "value") // ✅ prefer to be registered |
| 76 | + |
| 77 | + // the following will register a single input (without register invoked) |
| 78 | + setValue("resultSingleNestedField", { test: "1", test2: "2" }) // 🤔 |
| 79 | + |
| 80 | + // with registered inputs, the setValue will update both inputs correctly. |
| 81 | + register("notRegisteredInput.test", "1") |
| 82 | + register("notRegisteredInput.test2", "2") |
| 83 | + setValue("notRegisteredInput", { test: "1", test2: "2" }) // ✅ sugar syntax to setValue twice |
| 84 | + ``` |
| 85 | + |
| 86 | +</Admonition> |
| 87 | + |
| 88 | +### Examples |
| 89 | + |
| 90 | +--- |
| 91 | + |
| 92 | +**Basic** |
| 93 | + |
| 94 | +```javascript sandbox="https://codesandbox.io/s/react-hook-form-v7-ts-setvalue-8z9hx" |
| 95 | +import { useForm } from "react-hook-form" |
| 96 | + |
| 97 | +const App = () => { |
| 98 | + const { register, setValue } = useForm({ |
| 99 | + firstName: "", |
| 100 | + }) |
| 101 | + |
| 102 | + return ( |
| 103 | + <form> |
| 104 | + <input {...register("firstName", { required: true })} /> |
| 105 | + <button onClick={() => setValue("firstName", "Bill")}>setValue</button> |
| 106 | + <button |
| 107 | + onClick={() => |
| 108 | + setValue("firstName", "Luo", { |
| 109 | + shouldValidate: true, |
| 110 | + shouldDirty: true, |
| 111 | + }) |
| 112 | + } |
| 113 | + > |
| 114 | + setValue options |
| 115 | + </button> |
| 116 | + </form> |
| 117 | + ) |
| 118 | +} |
| 119 | +``` |
| 120 | + |
| 121 | +**Dependant Fields** |
| 122 | + |
| 123 | +```typescript sandbox="https://codesandbox.io/s/dependant-field-dwin1" |
| 124 | +import * as React from "react"; |
| 125 | +import { useForm } from "react-hook-form"; |
| 126 | + |
| 127 | +type FormValues = { |
| 128 | + a: string; |
| 129 | + b: string; |
| 130 | + c: string; |
| 131 | +}; |
| 132 | + |
| 133 | +export default function App() { |
| 134 | + const { watch, register, handleSubmit, setValue, formState } = useForm< |
| 135 | + FormValues |
| 136 | + >({ |
| 137 | + defaultValues: { |
| 138 | + a: "", |
| 139 | + b: "", |
| 140 | + c: "" |
| 141 | + } |
| 142 | + }); |
| 143 | + const onSubmit = (data: FormValues) => console.log(data); |
| 144 | + const [a, b] = watch(["a", "b"]); |
| 145 | + |
| 146 | + React.useEffect(() => { |
| 147 | + if (formState.touchedFields.a && formState.touchedFields.b && a && b) { |
| 148 | + setValue("c", `${a} ${b}`); |
| 149 | + } |
| 150 | + }, [setValue, a, b, formState]); |
| 151 | + |
| 152 | + return ( |
| 153 | + <form onSubmit={handleSubmit(onSubmit)}> |
| 154 | + <input {...register("a")} placeholder="a" /> |
| 155 | + <input {...register("b")} placeholder="b" /> |
| 156 | + <input {...register("c")} placeholder="c" /> |
| 157 | + <input type="submit" /> |
| 158 | + |
| 159 | + <button |
| 160 | + type="button" |
| 161 | + onClick={() => { |
| 162 | + setValue("a", "what", { shouldTouch: true }); |
| 163 | + setValue("b", "ever", { shouldTouch: true }); |
| 164 | + }} |
| 165 | + > |
| 166 | + trigger value |
| 167 | + </button> |
| 168 | + </form> |
| 169 | + ); |
| 170 | +} |
| 171 | +``` |
| 172 | + |
| 173 | +### Video |
| 174 | + |
| 175 | +--- |
| 176 | + |
| 177 | +<YouTube youTubeId="qpv51sCH3fI" /> |
0 commit comments