react-hook-form의 getValues와 setValue를 이용하여 커스텀 훅을 만들때 Path<T> 에러
Emoji 부분을 comment 와 comment 답글 그리고 post글 작성시에 쓰기 때문에 중복 코드가 발생할것으로 생각들어
useEmoji 라는 커스텀훅을 react-hook-form의 getValue와 setValue를 이용하여 만들려고 했는데,
제네릭으로 field name을 받아와서 사용하게끔 만드는데,
import { EmojiClickData } from 'emoji-picker-react';
import { useState } from 'react';
import {
UseFormGetValues,
UseFormSetValue,
FieldValues,
} from 'react-hook-form';
export const useEmoji = <T extends FieldValues>(
getValues: UseFormGetValues<T>,
setValue: UseFormSetValue<T>,
) => {
const [isEmoji, setIsEmoji] = useState<boolean>(false);
const handleEmojiView = () => {
setIsEmoji(!isEmoji);
};
const handlesetValueAddEmoji = (
emojiData: EmojiClickData,
valueKey: string,
) => {
const currentComment = getValues(valueKey); // 현재 입력된 댓글을 가져옴
setValue(valueKey, currentComment + emojiData.emoji);
handleEmojiView();
};
return {
isEmoji,
setIsEmoji,
handleEmojiView,
};
};
UseFormGetValue와, UseFormSetValue의 type d.ts를 보고 FieldValues를 제네릭에 extends 해주고 쓰면 될줄 알았는데,
getValues를 사용할때 Path<T>와 string타입이 다르다는 에러가 발생함.
아래와 같이 수정하여 해결했다 ㅠㅠ
import { EmojiClickData } from 'emoji-picker-react';
import { useState } from 'react';
import {
UseFormGetValues,
UseFormSetValue,
FieldValues,
FieldPath,
PathValue,
} from 'react-hook-form';
export const useEmoji = <T extends FieldValues>(
getValues: UseFormGetValues<T>,
setValue: UseFormSetValue<T>,
) => {
const [isEmoji, setIsEmoji] = useState<boolean>(false);
const handleEmojiView = () => {
setIsEmoji(!isEmoji);
};
const handlesetValueAddEmoji = (
emojiData: EmojiClickData,
valueKey: FieldPath<T>,
) => {
const currentComment = (getValues(valueKey) + emojiData.emoji) as PathValue<
T,
FieldPath<T>
>; // 현재 입력된 댓글과 emoji를 합쳐줌.
setValue(valueKey, currentComment);
handleEmojiView();
};
return {
isEmoji,
setIsEmoji,
handleEmojiView,
handlesetValueAddEmoji,
};
};
FieldPath라는놈을 써야함
-Reference
Argument of type 'string' is not assignable to parameter of type '`${string}` | `${string}.${string}` | `${string}.${number}`'
I've migrated react-hook-forms from v.6 to v.7. After changing the register method, as pointed out in the migration guide, the following error occurs: Argument of type 'string' is not assignable to
stackoverflow.com
https://github.com/orgs/react-hook-form/discussions/8025
How to replicate Path<T> · react-hook-form · Discussion #8025
Hi, I've created a component like so: import { ReactElement } from "react"; import { Placeholder, TextField, TextFieldProps } from "@aws-amplify/ui-react"; import { useController } from "react-hook...
github.com