From 7ecef7679fabcddf4e5667be0c3fef4ef4526f68 Mon Sep 17 00:00:00 2001 From: cfngc4594 Date: Tue, 18 Mar 2025 22:50:59 +0800 Subject: [PATCH] feat(credentials-sign-in-form): add loading state, error handling, and navigation after sign in --- src/components/credentials-sign-in-form.tsx | 30 ++++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/components/credentials-sign-in-form.tsx b/src/components/credentials-sign-in-form.tsx index 0706abd..a597891 100644 --- a/src/components/credentials-sign-in-form.tsx +++ b/src/components/credentials-sign-in-form.tsx @@ -9,11 +9,13 @@ import { FormLabel, FormMessage, } from "@/components/ui/form"; -import { useState } from "react"; +import { toast } from "sonner"; import { authSchema } from "@/lib/zod"; import { useForm } from "react-hook-form"; +import { useRouter } from "next/navigation"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; +import { useState, useTransition } from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { signInWithCredentials } from "@/app/actions/auth"; import { EyeIcon, EyeOffIcon, MailIcon } from "lucide-react"; @@ -21,6 +23,10 @@ import { EyeIcon, EyeOffIcon, MailIcon } from "lucide-react"; export type CredentialsSignInFormValues = z.infer; export function CredentialsSignInForm() { + const router = useRouter(); + const [isPending, startTransition] = useTransition(); + const [isVisible, setIsVisible] = useState(false); + const form = useForm({ resolver: zodResolver(authSchema), defaultValues: { @@ -29,11 +35,21 @@ export function CredentialsSignInForm() { }, }); - const [isVisible, setIsVisible] = useState(false); - const toggleVisibility = () => setIsVisible((prevState) => !prevState); + const toggleVisibility = () => setIsVisible((prev) => !prev); - const onSubmit = async (data: CredentialsSignInFormValues) => { - await signInWithCredentials(data); + const onSubmit = (data: CredentialsSignInFormValues) => { + startTransition(async () => { + const result = await signInWithCredentials(data); + + if (result?.error) { + toast.error("Sign In Failed", { + description: result.error, + }); + } else { + toast.success("Signed In Successfully"); + router.push("/dashboard"); + } + }); }; return ( @@ -92,8 +108,8 @@ export function CredentialsSignInForm() { )} /> -