0
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-hook-formで初期値を設定する方法

Posted at

react-hook-fromで初期値を設定する方法を3つご紹介します。

defaultValues

1つ目はdefaultValuesを使う方法です。
この方法が一番一般的だと思います。

import { useEffect } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';

type Inputs = {
  name: string;
};


const Sample = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Inputs>({
    defaultValues: { name: '田中太郎' }
  });

  const onSubmit: SubmitHandler<Inputs> = (data) => {
    console.log(data);
  };

  return (
      <form onSubmit={handleSubmit(onSubmit)}>
          <input
            {...register('name', {
            required: true,
            })}
          />
        <button type="submit">Submit</button>
      </form>
  );
}

export default Sample;

setValue

import { useEffect } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';

type Inputs = {
  name: string;
};


const Sample = () => {
  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<Inputs>();

  const onSubmit: SubmitHandler<Inputs> = (data) => {
    console.log(data);
  };

  useEffect(() => {
    setValue('name', '田中太郎')
  }, [])

  return (
      <form onSubmit={handleSubmit(onSubmit)}>
          <input
            {...register(`name`, {
            required: true,
            })}
          />
        <button type="submit">Submit</button>
      </form>
  );
}

export default Sample;

reset

import { useEffect } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';

type Inputs = {
  name: string;
};


const Sample = () => {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<Inputs>();

  const onSubmit: SubmitHandler<Inputs> = (data) => {
    console.log(data);
  };

  useEffect(() => {
    reset({ name: '田中太郎' })
  }, [])

  return (
      <form onSubmit={handleSubmit(onSubmit)}>
          <input
            {...register(`name`, {
            required: true,
            })}
          />
        <button type="submit">Submit</button>
      </form>
  );
}

export default Sample;

SWRで取得した値を初期値に設定する方法

SWRなどでAPIから取得した値を初期値に設定したい場合もあると思いますが、その方法です。

"use client";

import useSWR from "swr";
import { useForm, SubmitHandler } from "react-hook-form";

type Inputs = {
  id: number;
  name: string;
};

const Sample = () => {
  const fetcher = async (url: string): Promise<Inputs> => {
    const response = await fetch(url);
    return response.json();
  };

  const { data, error, isLoading } = useSWR<Inputs>(
    "http://localhost:3100/api/users/3",
    fetcher
  );

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Inputs>({
    defaultValues: {},
    values: data,
  });

  const onSubmit: SubmitHandler<Inputs> = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("name", {
          required: true,
        })}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default Sample;
0
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
0
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?