0

Столкнулась с проблемой при работе с react-hook-form. Когда я передаю методы через FormProvider и пытаюсь получить их в другом компоненте через useFormContext, появляется ошибка:

register = null

Хук useVerify.ts

import { yupResolver } from "@hookform/resolvers/yup";
import { verificationSchema } from "@/pages/Form/utils/schema";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { IVerificationData } from "@/types/FormData";
import { formService } from "@/services/form.service";
import { useErrorStore } from "@/store/ErrorStore";
export default function useVerify() {
 const methods = useForm({
 resolver: yupResolver(verificationSchema),
 defaultValues: {
 email: localStorage.getItem("registeredEmail") || "",
 otp: ["", "", "", "", "", ""],
 },
 });
 const setError = useErrorStore((state) => state.setError);
 const navigate = useNavigate();
 const onSubmit = async (data: IVerificationData) => {
 setError(false, "");
 const code = (data.otp || []).join("");
 console.debug("code:", code);
 try {
 const res = await formService.verifyUser(
 localStorage.getItem("registeredEmail") || "",
 code
 );
 console.log("🟢 Server response:", res);
 navigate("/login");
 localStorage.removeItem("registeredEmail");
 } catch (err: any) {
 const message =
 err.response?.data?.message ||
 err.response?.data?.error ||
 err.message ||
 "Unknown error";
 console.error(message);
 setError(true, message);
 }
 };
 return {
 ...methods,
 onSubmit,
 };
}

Компонент Verification.tsx

import { FormProvider } from "react-hook-form";
import { components } from "@/components/index";
import { useErrorStore } from "@/store/ErrorStore";
import useVerify from "@/hooks/useVerify";
export default function Verification() {
 const { isError } = useErrorStore((state) => state);
 const methods = useVerify();
 return (
 <FormProvider {...methods}>
 <form
 onSubmit={methods.handleSubmit(methods.onSubmit)}
 className="form__wrapper"
 >
 {isError && <components.Error />}
 <div className="form__container">
 <components.FormTitle
 title="Верифікація"
 underTitle="Введіть код, надісланий на вашу пошту"
 />
 <components.OtpInputs />
 <components.FormButton
 text="Підтвердити"
 isLoading={methods.formState.isSubmitting}
 />
 </div>
 </form>
 </FormProvider>
 );
}

Компонент OtpInputs.tsx

import { useState, useRef, useEffect } from "react";
import { useFormContext } from "react-hook-form";
export default function OtpInputs() {
 const { register, setValue } = useFormContext();
 const [otp, setOtp] = useState(["", "", "", "", "", ""]);
 const inputsRef = useRef<(HTMLInputElement | null)[]>([]);
 useEffect(() => {
 inputsRef.current[0]?.focus();
 }, []);
 const handleChange = (index: number, value: string) => {
 const upper = value.slice(-1).toUpperCase();
 const newValues = [...otp];
 newValues[index] = upper;
 setOtp(newValues);
 setValue("otp", newValues);
 if (upper && index < otp.length - 1) {
 inputsRef.current[index + 1]?.focus();
 }
 };
 const handleKeyDown = (index: number, e: React.KeyboardEvent) => {
 if (e.key === "Backspace" && !otp[index] && index > 0) {
 inputsRef.current[index - 1]?.focus();
 }
 };
 return (
 <section className="otp__section">
 {otp.map((val, index) => (
 <input
 key={index}
 type="text"
 inputMode="numeric"
 {...register?.(`otp.${index}`)}
 ref={(el: any) => (inputsRef.current[index] = el)}
 maxLength={1}
 className="otp__input"
 value={val}
 onChange={(e) => handleChange(index, e.target.value)}
 onKeyDown={(e) => handleKeyDown(index, e)}
 />
 ))}
 </section>
 );
}
задан 11 нояб. 2025 в 12:43
1
  • Пожалуйста, уточните вашу конкретную проблему или приведите более подробную информацию о том, что именно вам нужно. В текущем виде сложно понять, что именно вы спрашиваете. Commented 11 нояб. 2025 в 13:15

0

Знаете кого-то, кто может ответить? Поделитесь ссылкой на этот вопрос по почте, через Твиттер или Facebook.

Ваш ответ

Черновик сохранён
Черновик удалён

Зарегистрируйтесь или войдите

Регистрация через Google
Регистрация через почту

Отправить без регистрации

Необходима, но никому не показывается

Отправить без регистрации

Необходима, но никому не показывается

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Начните задавать вопросы и получать на них ответы

Найдите ответ на свой вопрос, задав его.

Задать вопрос

Изучите связанные вопросы

Посмотрите похожие вопросы с этими метками.