Next.js Discord

Discord Forum

"Context" is not a function

Answered
`icey tea dev` posted this in #help-forum
Open in Discord
I've setup my own sessionContext (without nextAuth) to give my clientside access to user elements such as email and role.
However, I'm getting the following error:
Error: (0 , _contexts_SessionProvider__WEBPACK_IMPORTED_MODULE_1__.useSession) is not a function


My exports for useSession are as follows:
export const useSession = () => {
  const context = useContext(AuthContext);

  if (!context) {
    throw new Error("useSession must be used within a SessionProvider");
  }

  return context;
};

export default SessionProvider;


I'm importing it like this:
import { useSession } from "../../../contexts/SessionProvider";


My imports are correct (as I'm getting autocomplete), so I'm unsure why it's saying it's not a function.
I also attached my file structure if that helps.
Answered by Ray
hook cannot be use in a server component
View full answer

18 Replies

where do you use the useSession hook?
I use it in a rooted layout
import { useSession } from "../../../contexts/SessionProvider";
import { Roles } from "@/types";
import { redirect } from "next/navigation";

export default function AdminLayout({
  children, // will be a page or nested layout
}: {
  children: React.ReactNode;
}) {
  const { isSignedIn, user, reload } = useSession();
  reload();

  return (
    <section>
      {isSignedIn && user
        ? user.role == Roles.ADMIN
          ? children
          : redirect("/not-authorized")
        : redirect("/not-authorized")}
    </section>
  );
}
this layout is in a folder called admin, which is inside the dashboard foler
hook cannot be use in a server component
Answer
ahhh and layouts are always servers components thats right
well you could make it client component but it is not recommented
is that so we don't re-render the layout content on each page?
no layout in client component still doesn't re-render on page change
but will cause all of its children to client component
so you can't use server api to it
I think you can extend the type of user in next-auth to pass the role to it?
then you can use getServerSession
@Ray I think you can extend the type of user in next-auth to pass the role to it?
I'm not using nextauth since I'm trying to raw dog it to learn how this all works lol
oh ok lol
either make it a server side api or use the hook in client component
@Ray either make it a server side api or use the hook in client component
I'll use the hook in client components, thank you. 🙏