Frontend/React

[Rect Hook Form] getValues()에서 Number 타입 가져오는 법

wam 2024. 12. 11. 23:31
import { useForm } from "react-hook-form";

interface IFormProps {
  name: string;
  price: string; // getValues()로 가져오는 값의 타입은 기본적으로 문자열(string)
  description: string;
}

const MyForm = () => {
  const {
    register,
    getValues,
    formState: { isValid, errors },
    handleSubmit
  } = useForm<IFormProps>({
    mode: "onChange",
  });

  const onSubmit = (data: IFormProps) => {
    const { name, price, description } = getValues();
	
    createDishMutation({
        variables: {
          input: {
            name,
            price +price, // +price : 형변환 (string -> number)
            description,
            restaurantId: +restaurantId
          }
        }
    });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("price", {
          required: "가격을 입력해 주세요.",
          min: {
            value: 0,
            message: "가격은 0 이상이어야 합니다.",
          },
        })}
        className="input"
        type="number"
        placeholder="가격"
      />
      <button type="submit">제출</button>
    </form>
  );
};

export default MyForm;
  • React Hook Form에서 getValues()로 가져오는 값의 타입기본적으로 문자열(string)이다.
  • 이는 HTML 폼 요소(<input>)가 값을 문자열로 반환하기 때문이다.
  • 심지어 type="number"로 설정된 <input>에서도 반환값은 문자열로 처리된다.

 

 

valueAsNumber 옵션 사용하여 숫자로 자동 변환하기

import { useForm } from "react-hook-form";

interface IFormProps {
  name: string;
  price: number; // number 타입
  description: string;
}

const MyForm = () => {
  const {
    register,
    getValues,
    formState: { isValid, errors },
    handleSubmit
  } = useForm<IFormProps>({
    mode: "onChange",
  });

  const onSubmit = (data: IFormProps) => {
    const { name, price, description } = getValues();
	
    createDishMutation({
        variables: {
          input: {
            name,
            price,
            description,
            restaurantId: +restaurantId
          }
        }
    });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("price", {
          required: "가격을 입력해 주세요.",
          valueAsNumber: true, // 값을 숫자로 변환
          min: {
            value: 0,
            message: "가격은 0 이상이어야 합니다.",
          },
        })}
        className="input"
        type="number"
        placeholder="가격"
      />
      <button type="submit">제출</button>
    </form>
  );
};

export default MyForm;