강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

작성자 없음

작성자 정보가 삭제된 글입니다.

아바타 커뮤니티앱 만들기 (React Native Expo)

[4-1] React Hook Form 도입(1) - 컴포넌트 분리

react-hook-form handleSubmit이 동작하지 않습니다

해결된 질문

작성

·

142

0

질문 작성시 꼭 참고해주세요

  • 에러 메세지에서 단서를 찾을 수 있는 경우가 많습니다. 에러 메세지를 읽고 한번 검색해보시는것을 추천드립니다.

  • 질문글을 작성하실때는, 현재 문제(또는 에러)와 코드나 github을 첨부해주세요.

  • 개발중인 OS, ReactNative, Node 버전 등의 개발환경을 알려주셔야합니다.

  • 에러메세지는 일부분이 아닌 전체 상황을 올려주세요. 일부만 보여주시면 답변이 어렵습니다.

  • 에러 잘라서 올리시면 안됩니다!

(에러 일부만 자르거나 일부만 복사하지말아주세요)

 

 

function EmailInput() {
    const { control } = useFormContext()
    return (
        <Controller
            name="email"
            control={control}
            render={({ field: { onChange, value } }) => (
                <InputField
                    label="이메일"
                    value={value}
                    onChangeText={onChange}
                    placeholder="이메일을 입력해주세요."
                />
            )}
        />
    )
}

// signup 페이지 마크업 부분입니다

const signupForm = useForm<FormValues>({
        defaultValues: {
            email: '',
            password: '',
            passwordConfirm: ''
        }
    })
    async function onSubmit(data: FormValues) {
        console.log(data)
    }
return (
        <FormProvider {...signupForm}>
            <View style={styles.container}>
                <EmailInput />
                <PasswordInput />
                <PasswordConfirmInput />
            </View>
            <FixedBottomCTA
                label="회원가입하기"
                onPress={() => {
                    console.log('onPress::::')
                    signupForm.handleSubmit(onSubmit)
                }}
            />
        </FormProvider>
    )


export default function FixedBottomCTA({ label, onPress }: FixedBottomCTAProps) {
    const inset = useSafeAreaInsets()
    return (
        <View style={[styles.fixed, { paddingBottom: inset.bottom || 12 }]}>
            <CustomButton label={label} onPress={onPress} />
        </View>
    )
}

function CustomButton({
    label, size = 'large', variant = 'filled',
    ...props
}: CustomButtonProps) {
    return (
        <CustomPressable
            style={({ pressed }) => [
                styles.container, styles[size], styles[variant],
                pressed && styles.pressed
            ]}
            {...props}
        >
            <Text style={styles[variant]}>{label}</Text>
        </CustomPressable>
    )
}


export const CustomPressable = ({ children, ...props }: PressableProps) => {
    const pressHandlerProps =
        Platform.OS === "android"
            ? { onPressIn: props.onPress || props.onPressIn }
            : { onPress: props.onPress };
    // console.log('pressHandlerProps:::::', pressHandlerProps)
    return (
        <Pressable {...props} {...pressHandlerProps}>{children}</Pressable>
    )
}

 node 20v

hookform 7.55v

ios android 동일 증상

react-native 0.76.9v 버전입니다.

하위 버튼 컴포넌트들에서 onPress 함수만 별도 분리하여 console 찍어봐도 동작하지 않고

signupForm.handleSubmit(onSubmit) 윗부분 console 만 실행되고 있습니다

차라리 터미널에 에러 코드라도 나타나면 좋은데 아예 아무런 반응이 없어서 해결에 애를 먹고 있습니다

답변 1

0

안녕하세요, 인프런 AI 인턴입니다. 형원님.

react-hook-formhandleSubmit이 예상대로 작동하지 않는 문제를 겪고 계신 것 같습니다. 코드 상에서 확인해 볼 몇 가지 포인트와 일반적인 이슈 해결 방법을 설명드리겠습니다.

문제 진단:

  1. handleSubmit 함수 호출 확인:

    • FixedBottomCTA에서 CustomButtononPresssignupForm.handleSubmit(onSubmit)을 포함하고 있습니다. 이 부분에서 handleSubmit이 직접 호출되지 않은 것 같습니다. onPress={() => signupForm.handleSubmit(onSubmit)}라고 함수를 직접 호출하는 것도 한 가지 방법입니다.
  2. 버튼 클릭 확인:

    • 버튼이 클릭됐을 때 동작하는지 확인해야 합니다. CustomButtononPress 이벤트가 제대로 실행되고 있는지 확인해 보세요. console.log를 추가하여 버튼 클릭 이벤트가 발생하는지 모니터링하시면 도움이 될 것입니다.
  3. useFormhandleSubmit 호출 위치 확인:

    • signupForm.handleSubmit(onSubmit)의 위치를 확인하여, onPress 이벤트 핸들러에서 호출되고 있는지 확인하세요. 이 경우, 버튼을 누를 때마다 handleSubmit이 실행되어야 합니다.
  4. React Hook Form Context 연결 확인:

    • FormProvider 컴포넌트에 useForm에서 반환한 모든 메소드를 제공하고, 각 필드에서 useFormContext를 사용하고 있는 것이 맞는지 확인해보세요.
  5. 에러 핸들링 추가:

    • handleSubmit이 오류 메시지를 출력하지 않는다면, 다음과 같은 방식으로 에러를 핸들링하도록 수정해 보세요:
    signupForm.handleSubmit(onSubmit, onError)();
    function onError(errors: any) {
       console.error("Validation errors: ", errors);
    }
    

유사한 질문:

이러한 방법들로 문제를 해결해 보시고, 궁금한 점이 있거나 추가적인 질문이 필요하다면 언제든지 문의해 주세요.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다. 현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏 추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.

작성자 없음

작성자 정보가 삭제된 글입니다.

질문하기