1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React×Typescript】react-hook-formのdefaultValuesにハマった話

Posted at

はじめに

今回、TODOアプリを作っています。
そこで起きた問題と解決した内容について
備忘録として書いておきます。

今回ハマった事象について

TODOの中身を編集するために、モーダルを出し、
それぞれのinputに値を持たせたいのに、
値が全然入ってこなかった。

defaultValuesに値をちゃんと渡しているのになぜだろうと思い、
色々試行錯誤すると、ドキュメントに書いてありました。

Important: defaultValues is cached at the first render within the custom hook. If you want to reset the defaultValues, you should use the reset api.

どうやら最初にしかキャッシュされないらしく、動的にしたいならresetとか使ったほうがいいよと言われていた。

解決方法

useForm<FormDataValidate>({
    defaultValues: defaultValues ?? {
      text: "",
      time: 0,
    },
  });
  useEffect(() => {
    reset(defaultValues);
  }, [defaultValues, reset]);

一部抜粋してみました。
useEffectを使ってこんな感じでやればOK

おわりに

とにかくハマっていたので解決できてよかったです。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?