"use client"; import { useState, useEffect } from "react"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import Link from "next/link"; // Removed the styles object for navbar export default function CreateTeam() { const { data: session, status } = useSession(); const [teamName, setTeamName] = useState(""); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(true); 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 { // 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 }), }); 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); // Force a session refresh to update the session with the new teamId await fetch("/api/auth/session", { method: "GET", credentials: "include", }); // Use window.location for a hard navigation to ensure session is fully updated window.location.href = `/${data.teamId}`; } catch (err) { console.error("Team creation error:", err); setError(err.message); setIsLoading(false); } }; if (isLoading) { return
{error}
}