MIF_E31221222/sigap-website/app/(pages)/(auth)/_handlers/use-sign-in.ts

80 lines
2.3 KiB
TypeScript

import { useNavigations } from "@/app/_hooks/use-navigations";
import { useSignInPasswordlessMutation } from "../_queries/mutations";
import { toast } from "sonner";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { ISignInPasswordlessSchema, SignInPasswordlessSchema } from "@/src/entities/models/auth/sign-in.model";
import { zodResolver } from "@hookform/resolvers/zod";
export function useSignInHandler() {
const { mutateAsync: signIn, isPending, error: errors } = useSignInPasswordlessMutation();
const { router } = useNavigations();
const [error, setError] = useState<string>();
const {
register,
reset,
formState: { errors: formErrors },
setError: setFormError,
} = useForm<ISignInPasswordlessSchema>({
defaultValues: {
email: "",
},
resolver: zodResolver(SignInPasswordlessSchema),
})
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (isPending) return;
setError(undefined);
const formData = new FormData(event.currentTarget);
const email = formData.get('email')?.toString();
const res = await signIn(formData);
if (!res?.error) {
toast('An email has been sent to you. Please check your inbox.');
if (email) router.push(`/verify-otp?email=${encodeURIComponent(email)}`);
} else {
setError(res.error);
}
};
// const onSubmit = handleSubmit(async (data) => {
// if (isPending) return;
// console.log(data);
// setError(undefined);
// const { email } = data;
// const formData = new FormData();
// formData.append('email', email);
// const res = await signIn(formData);
// if (!res?.error) {
// toast('An email has been sent to you. Please check your inbox.');
// router.push(`/verify-otp?email=${encodeURIComponent(email)}`);
// } else {
// setError(res.error);
// }
// })
return {
// formData,
// handleChange,
reset,
register,
handleSignIn: handleSubmit,
error,
isPending,
errors: !!error || errors,
};
}