2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

react-hook-formのuseFieldArrayのidは勝手に上書きされる件

Posted at

はじめに

みなさん、こんにちは torihaziです

花粉症です。鼻がぴえんです。

結論

useForm定義時にapiを通じてbackendから取得してきた配列(itemsとする)を元にuseFieldArrayを使用し、その戻り値であるfieldsの各idと元々のitemsの各idは一致しない。
useFieldArrayはidを勝手に上書きする。

useFieldArray automatically generates a unique identifier named id which is used for key prop. For more information why this is required: https://react.dev/learn/rendering-lists
https://react-hook-form.com/docs/usefieldarray

例えば

fields.map((field,index)=> <Hoge id={field.id} key={field.id} />)

みたいにして描画した際に対応するindexのitemsのidとfieldsのidは一致しない。

そのため、各フォームが独立していてそのフォーム内で元々のidを使用したい場合、

form.getValues(`配列の名前.${index}.id`)

としなきゃダメ。

useFormのhandleSubmitを通せばその問題は気にしなくて良くなる

form.handleSubmit(
    // onValid
    (data) => {
      update({
        ...data.items?.[index],
        title: 値
      };
    },
)();

終わりに

追加可能フォームを作成し、各フォームが独立してsubmit可能であるようなものを作ってました。
update等もできるようにしたところ、そのidを指定してupdateできるようなものです。
最初はこれを知らずにいくらリクエストしても"Record Not Found"であり、そんなバカなと思ってbackendの全テーブルを検索したにも関わらず存在しないidと言われて萎えてました。

こういうことだったんですね。納得です。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?