diff --git a/actions/auth-actions.ts b/actions/auth-actions.ts index 728eed1..39d8a34 100644 --- a/actions/auth-actions.ts +++ b/actions/auth-actions.ts @@ -76,8 +76,9 @@ export async function signin(previousState: ActionState, formData: FormData) { redirect(`/auth/verify-otp?phone_number=${FORMATTED_MOBILE_NUMBER}`); } -type ActionState = { +export type ActionState = { message: string; + status: string; payload?: FormData; }; diff --git a/components/auth/verify-registration-otp-form.tsx b/components/auth/verify-registration-otp-form.tsx index d60d739..301c63a 100644 --- a/components/auth/verify-registration-otp-form.tsx +++ b/components/auth/verify-registration-otp-form.tsx @@ -3,58 +3,30 @@ import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { VerifyRegistrationOTP } from "@/queries/authentication"; import { zodResolver } from "@hookform/resolvers/zod"; import { Loader2 } from "lucide-react"; import { signIn } from "next-auth/react"; import Link from "next/link"; -import { useRouter, useSearchParams } from "next/navigation"; -import { useTransition } from "react"; -import { type SubmitHandler, useForm } from "react-hook-form"; -import { toast } from "sonner"; -import { z } from "zod"; -const OTPSchema = z.object({ - pin: z.string().min(6, { - message: "OTP is required.", - }), -}); +import { redirect, useRouter, useSearchParams } from "next/navigation"; +import { useActionState } from "react"; export default function VerifyRegistrationOTPForm({ phone_number, }: { phone_number: string }) { - const [isPending, startTransition] = useTransition(); - const router = useRouter(); console.log("verification in OTP form", phone_number); - const { - register, - handleSubmit, - formState: { errors }, - } = useForm>({ - defaultValues: { - pin: "", - }, - resolver: zodResolver(OTPSchema), - }); - const searchParams = useSearchParams(); - const callbackUrl = searchParams.get("callbackUrl") || "/dashboard"; - const onSubmit: SubmitHandler> = (data) => { - startTransition(async () => { - const nextAuth = await signIn("credentials", { - pin: data.pin, - callbackUrl, - redirect: false, - }); - if (!nextAuth?.error) { - router.push("/devices"); - } else { - toast.error(JSON.parse(nextAuth?.error ?? "").message); - } - }); - }; + const searchParams = useSearchParams(); + const mobile = searchParams.get("phone_number"); + if (!mobile) redirect("/auth/login"); + const [state, formAction, isPending] = useActionState(VerifyRegistrationOTP, { + message: "", + status: "", + }); return (
@@ -66,16 +38,24 @@ export default function VerifyRegistrationOTPForm({ + - {errors.pin && ( -

{errors.pin.message}

+ {state?.status === "error" && ( +

{state.message}

)}