"use client"; import { useState, useEffect } from "react"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import Link from "next/link"; export default function CreateTeam() { const { data: session, status, update: updateSession } = useSession(); const [teamName, setTeamName] = useState(""); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(true); const [success, setSuccess] = useState(false); const router = useRouter(); useEffect(() => { if (status === "authenticated") { if (session?.user?.teamId) { router.push(`/${session.user.teamId}`); } else { setIsLoading(false); } } else if (status === "unauthenticated") { router.push("/login"); } }, [status, session, router]); const handleCreateTeam = async (e) => { e.preventDefault(); setIsLoading(true); setError(""); try { // Validate team name if (!teamName || teamName.trim() === "") { throw new Error("Team name is required"); } // Check session status before proceeding if (status !== "authenticated") { throw new Error("You must be logged in to create a team"); } const response = await fetch("/api/teams/create", { method: "POST", headers: { "Content-Type": "application/json", }, credentials: "include", // Important: include credentials with the request body: JSON.stringify({ name: teamName.trim() }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || "Failed to create team"); } console.log("Team created successfully with ID:", data.teamId); setSuccess(true); // Try to update the session with the new team ID try { // Wait briefly to ensure DB changes are reflected await new Promise((resolve) => setTimeout(resolve, 500)); await updateSession(); // Update the NextAuth session if possible } catch (sessionErr) { console.warn( "Session update failed, using redirect instead:", sessionErr ); } // Use window.location for a hard navigation to ensure session is fully updated setTimeout(() => { window.location.href = `/${data.teamId}`; }, 1000); } catch (err) { console.error("Team creation error:", err); setError(err.message); } finally { setIsLoading(false); } }; if (isLoading && !success) { return
Loading...
; } return (
Create Team
{success ? (
✅

Team Created Successfully!

Redirecting to your new team page...

) : ( <>

Create a New Team

setTeamName(e.target.value)} required className="auth-input" maxLength={50} />
{error &&

{error}

} )}
); }