コンテンツにスキップ

setValue

フィールドの値を更新

setValue (name: string, value: unknown, config?: Object) => void

この関数を使用すると、動的に値を設定できます。 登録済みフィールドの値と、フォームの状態を検証および更新するオプションがあります。同時に、不要な再レンダリングを回避しようとします。

プロパティ

名前説明
namestring
  • 名前で単一のフィールドを対象にします。

  • フィールド配列と組み合わせて使用する場合。

    • 次のようなメソッドを使用できます。 replace または update フィールド配列の場合、ただし、これらはターゲットのフィールド配列のためにコンポーネントのアンマウントと再マウントを引き起こします。

      const { update } = useFieldArray({ name: 'array' });
      // unmount fields and remount with updated value
      update(0, { test: '1', test1: '2' })
      // will directly update input value
      setValue('array.0.test1', '1');
      setValue('array.0.test2', '2');
    • 存在しないフィールドをターゲットにするときに、新しいフィールドを作成しません。

      const { replace } = useFieldArray({ name: 'test' })
      // ❌ doesn't create new input
      setValue('test.101.data')
      // ✅ work on refresh entire field array
      replace([{data: 'test'}])
valueunknown

フィールドの値。この引数は必須であり、undefinedにすることはできません。

optionsshouldValidateboolean
  • 入力が有効かどうかを計算するかどうか(購読している場合 errors).

  • フォーム全体が有効かどうかを計算するかどうか(購読している場合 isValid).

  • このオプションは、指定されたフィールドレベルでtouchedFieldsを更新します。フォーム全体のタッチされたフィールドではありません
setValue('name', 'value', { shouldValidate: true })
shouldDirtyboolean
  • 入力がデフォルト値に対してダーティであるかどうかを計算するかどうか(購読している場合 dirtyFields).

  • フォーム全体がデフォルト値に対してダーティであるかどうかを計算するかどうか(購読している場合 isDirty).

  • このオプションは、指定されたフィールドレベルでdirtyFieldsを更新します。フォーム全体のダーティフィールドではありません
setValue('name', 'value', { shouldDirty: true })
shouldTouchboolean

入力をタッチされた状態にするかどうか。

setValue('name', 'value', { shouldTouch: true })

ルール

  • 次の条件のみが再レンダリングをトリガーします

    • 値の更新によってエラーがトリガーまたは修正された場合

    • setValueによって、ダーティやタッチなどの状態が更新された場合。

  • 2番目の引数をネストされたオブジェクトにするのではなく、フィールドの名前をターゲットにすることをお勧めします。

    setValue('yourDetails.firstName', 'value'); // ✅ performant
    setValue('yourDetails', { firstName: 'value' }); // less performant
    register('nestedValue', { value: { test: 'data' } }); // register a nested value input
    setValue('nestedValue.test', 'updatedData'); // ❌ failed to find the relevant field
    setValue('nestedValue', { test: 'updatedData' } ); // ✅ setValue find input and update
  • 呼び出す前に、入力の名前を登録することをお勧めします setValue。フィールド配列全体を更新するには、最初にuseFieldArrayフックが実行されていることを確認してください。

    重要:useFieldArrayから replace を使用してください。setValueによるフィールド配列全体の更新は、次のメジャーバージョンで削除されます。

    // you can update an entire Field Array,
    setValue('fieldArray', [{ test: '1' }, { test: '2' }]); // ✅
    // you can setValue to a unregistered input
    setValue('notRegisteredInput', 'value'); // ✅ prefer to be registered
    // the following will register a single input (without register invoked)
    setValue('resultSingleNestedField', { test: '1', test2: '2' }); // 🤔
    // with registered inputs, the setValue will update both inputs correctly.
    register('notRegisteredInput.test', '1')
    register('notRegisteredInput.test2', '2')
    setValue('notRegisteredInput', { test: '1', test2: '2' }); // ✅ sugar syntax to setValue twice

CodeSandbox JS
import { useForm } from "react-hook-form";
const App = () => {
const { register, setValue } = useForm();
return (
<form>
<input {...register("firstName")} />
<button type="button" onClick={() => setValue("firstName", "Bill")}>
setValue
</button>
<button
type="button"
onClick={() =>
setValue("lastName", "firstName", {
shouldValidate: true,
shouldDirty: true
})
}
>
setValue options
</button>
</form>
);
};
import * as React from "react";
import { useForm } from "react-hook-form";
type FormValues = {
a: string;
b: string;
c: string;
};
export default function App() {
const { watch, register, handleSubmit, setValue, formState } = useForm<
FormValues
>({
defaultValues: {
a: "",
b: "",
c: ""
}
});
const onSubmit = (data: FormValues) => console.log(data);
const [a, b] = watch(["a", "b"]);
React.useEffect(() => {
if (formState.touchedFields.a && formState.touchedFields.b && a && b) {
setValue("c", `${a} ${b}`);
}
}, [setValue, a, b, formState]);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("a")} placeholder="a" />
<input {...register("b")} placeholder="b" />
<input {...register("c")} placeholder="c" />
<input type="submit" />
<button
type="button"
onClick={() => {
setValue("a", "what", { shouldTouch: true });
setValue("b", "ever", { shouldTouch: true });
}}
>
trigger value
</button>
</form>
);
}

動画

次のビデオチュートリアルでは、setValueAPIについて詳しく説明します。

ご支援ありがとうございます

プロジェクトでReact Hook Formが役立つと思われる場合は、スターを付けてサポートすることを検討してください。