Mastering React Hook Form: A Comprehensive Guide
Chen Han
Chen Han
React Hook Form With Typescript
import {
currentSnackbarState,
emailState,
forgotPassState,
modalOpenState,
} from "@/recoils";
import * as yup from "yup";
import { useState } from "react";
import classname from "classnames";
import { email } from "@/util/yup";
import { useRouter } from "next/router";
import Button from "@/components/Button";
import Input from "@/components/ReactInput";
import httpService from "@/services/httpService";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm, SubmitHandler, FieldValues } from "react-hook-form";
import { useRecoilState, useResetRecoilState, useSetRecoilState } from "recoil";
const schema = yup
.object({
email: email(yup),
})
.required();
type FormValues = {
email: string;
};
type HandlePasswordResetFn = (data: FormValues) => Promise<void>;
export default function ForgotPassword() {
const resetEmail = useResetRecoilState(emailState);
const setCurrentSnackBar = useSetRecoilState(currentSnackbarState);
const [modalState,] = useRecoilState(modalOpenState);
/* modal state */
const [, setForgotPassword] = useRecoilState(forgotPassState);
const [load, setLoad] = useState(false)
const handlePasswordReset: HandlePasswordResetFn = async (data) => {
setLoad(true)
if (data.email) {
const { data: { success } } = await httpService.post("/api/user/password/reset", { email: data.email })
success
? setCurrentSnackBar(() => ({
display: true,
type: "success",
heroText: "success",
subText: "A reset password link has been sent to your email.",
bodyText: "A reset password link has been sent to your email.",
}))
: setCurrentSnackBar(() => ({
display: true,
type: "error",
heroText: "error",
subText: "Unexpected Error",
bodyText: "Unexpected Error",
}));
resetEmail();
setLoad(false)
}
};
const onSubmit: SubmitHandler<FieldValues> = async (data) => {
await handlePasswordReset({ email: data.email });
};
/* everything about the form */
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: yupResolver(schema),
});
/* checkout page */
const router = useRouter();
const checkoutPage = router.route === "/checkout";
return (
<div className={classname(
"max-w-sm m-auto",
checkoutPage && "mt-2",
!modalState && !checkoutPage && "mt-40",
modalState && "mt-4"
)}>
<form onSubmit={handleSubmit(onSubmit)}>
<Input
column="email"
register={register}
errors={errors}
required
className={classname("h-[80px]", checkoutPage ? "h-[60px]" : "h-[80px]")}
/>
{
checkoutPage &&
<div
className="ml-auto text-right cursor-pointer text-blue-600 dark:text-blue-500 hover:underline"
onClick={(e) => {
setForgotPassword(false);
}}
>
Go back to login
</div>
}
<Button
buttonType="submit"
className="my-1 mt-4 w-[-webkit-fill-available]"
innerDivClassName="w-[-webkit-fill-available]"
text="Send reset link"
arrow
type="primary"
loading={load}
loadingText="processing..."
/>
</form>
</div>
);
}