LoginSignup
96
104

More than 1 year has passed since last update.

【React / Next】SWRなどでfetchしたデータをreact-hook-formへ流し込んで、取得したデータを初期値として表示させたい

Posted at

編集画面でfetchデータをフォームへ初期表示させたかったので、その備忘録です。
なお、FormControl などは chakra-ui を使用した環境で行いました。

環境

  • next: 11.1.3
  • react: 17.0.2
  • react-hook-form: ^7.28.0
  • @chakra-ui/react: ^1.8.5

だめだったコード

  • useForm の defaultValues へセットするだけ
  • 固定値を defaultValues へセットすると表示されたが、fetchData は初期表示されなかった
export const Form = () => {
  // 省略
  const { data, error } = useSWR("/api/user", fetcher);

  const {
    handleSubmit,
    control,
    formState: { errors },
  } = useForm({
    // 固定値であれば表示された
    defaultValues: { name: data.name },
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      // 省略
    </form>
}

初期表示されたコード

  • useEffect と useForm の reset を使用する
  • 親コンポーネントで fetch して、props で渡す場合も同様に初期表示できた
export const Form = () => {
  // 省略
  const { data, error } = useSWR("/api/user", fetcher);

  const {
    handleSubmit,
    control,
    formState: { errors },
    reset,
  } = useForm();

  useEffect(() => {
    reset({
      ...data,
      status: data?.status.toString(),
    });
  }, [data, reset]);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      // 省略
    </form>
}

文献

96
104
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
96
104