"use client"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { LoginSchema, type LoginInput } from "@/lib/schemas"; import { loginUser } from "@/lib/actions/auth"; import { useToast } from "@/hooks/use-toast"; import { useState } from "react"; import { Loader2 } from "lucide-react"; // No longer need useRouter for post-login navigation if server action redirects export function LoginForm() { const { toast } = useToast(); const [isLoading, setIsLoading] = useState(false); const form = useForm({ resolver: zodResolver(LoginSchema), defaultValues: { email: "", password: "", }, }); async function onSubmit(values: LoginInput) { setIsLoading(true); try { const result = await loginUser(values); // This action will now redirect on success // If the action returns (i.e., did not redirect), it means there was an error. if (result && result.success === false) { toast({ title: "Login Failed", description: result.message, variant: "destructive", }); } // Successful login will result in a redirect handled by Next.js, // so client-side navigation or refresh is no longer needed here. // The "Login Successful" toast is removed as the page will change. } catch (error: any) { // Server actions that redirect throw a special error that Next.js catches. // We should not show this as a user-facing toast. if (error.message?.includes('NEXT_REDIRECT')) { // This is an expected error during redirect, let Next.js handle it. // console.log("Caught NEXT_REDIRECT, letting Next.js handle it."); } else { toast({ title: "Error", description: error.message || "An unexpected error occurred. Please try again.", variant: "destructive", }); } } finally { setIsLoading(false); } } return (
( Email )} /> ( Password )} /> ); }