I have a sign in button in my navbar component. I want it to only show if the user has signed in. The checks would be done using session hooks.
But now, I need to manually refresh the page in order to see the changes. For example, when i signed in into the web app through the page /auth/login, the middleware will redirect to /config/profile. But the navbar will still not change the ui: the sign in button will still be showing.
I tried to use useEffect, onclick = () => router.push as well as router.reload and router.refresh but nothing works. They dont seem to refresh the nav bar. I still had to f5 refresh the page manually.
//src/components/main-nav.tsx
//this is the navbar component
"use client"
import * as React from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { docsConfig } from "@/config/docs";
import { siteConfig } from "@/config/site";
import { cn } from "@/lib/utils";
import { Icons } from "@/components/icons";
import { LoginButton } from "./auth/login-button";
import { Button } from "./ui/button";
import { UserButton } from "@/components/auth/user-button";
import { useSession } from "next-auth/react";
import { useRouter } from 'next/navigation'
export function MainNav() {
const pathname = usePathname();
const { data: session, status } = useSession();
// Log the current session
React.useEffect(() => {
console.log("[main-nav-tsx][session]", { session });
if (!session) {
console.log("[main-nav-tsx][session] NO USER SIGNED IN");
} else {
console.log("[main-nav-tsx][session] USER SIGNED IN", session.user);
}
}, [session]);
const router = useRouter()
return (
<div className="mr-4 hidden md:flex">
<Link href="/" className="mr-6 flex items-center space-x-2">
<Icons.logo className="h-6 w-6" />
<span className="hidden font-bold sm:inline-block">
{siteConfig.name}
</span>
</Link>
<nav className="flex items-center gap-4 text-sm lg:gap-6">
{docsConfig.mainNav?.map((item) =>
item.href ? (
<Link
key={item.href}
href={item.href}
className={cn(
"transition-colors hover:text-foreground/80",
pathname === item.href
? "text-foreground"
: "text-foreground/60"
)}
>
{item.title}
</Link>
) : null
)}
{/* user button is to be shown only when user is logged in.
otherwise, show sign in.
it works, but it doesnt auto refresh, i have to manually refresh the page */}
{!session && (
<LoginButton>
<Button>Sign in</Button>
</LoginButton>
)}
</nav>
</div>
);
}