Next.js Discord

Discord Forum

useSession not reactive on client side?

Unanswered
Kurilian Bobtail posted this in #help-forum
Open in Discord
Kurilian BobtailOP
Using JSAuth v5

if a user clicks on the signout component, the session in useSession is not triggered in the useEffect... i have to refresh the page to get the user's logout state

My goal is that when a user is signed in, the ClientSessionTest renders you are logged in, welcome and then when i click on log out You are not authorized to view this page!

When I click sign out my user is signed out but i have to refresh the page for you are logged in, welcome to render You are not authorized to view this page!

"use client";

import { useSession } from "next-auth/react";
import { useEffect } from "react";

import { signIn, signOut } from "auth";
import { Button } from "./ui/button";

export function SignIn({
  provider,
  orRegister = false,
  ...props
}: { provider?: string; orRegister?: boolean } & React.ComponentPropsWithRef<
  typeof Button
>) {
  return (
    <form
      action={async () => {
        "use server";
        await signIn(provider);
      }}
    >
      <Button {...props}>Sign In {orRegister && "or Register"}</Button>
    </form>
  );
}

export function SignOut(props: React.ComponentPropsWithRef<typeof Button>) {
  return (
    <form
      action={async () => {
        "use server";
        await signOut();
      }}
      className="w-full"
    >
      <Button variant="ghost" className="w-full p-0" {...props}>
        Sign Out
      </Button>
    </form>
  );
}


export default function ClientSessionTest() {
  const { data: session, status } = useSession();

  useEffect(() => {
    console.log(status);
  }, [status]);

  if (status === "loading") {
    return <p>Loading...</p>;
  }

  if (session?.user) {
    return <p className="text-green-500">You are logged in, welcome!</p>;
  }

  return (
    <p className="text-red-500">You are not authorized to view this page!</p>
  );
}

0 Replies