skip to Main Content
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body >
        <SessionProvider >
        <Toaster/>
        <RegisterModal/>
        <LoginModal/>
        <Layouts>
        {children}
        </Layouts>
        </SessionProvider>
        </body>
    </html>

Help me to extract sessions so that I can pass it to the <SessionProvider> , I don’t know how to extract the session object. I can have only children.

2

Answers


  1. make a function;

    "use server";
    import { cookies } from "next/headers";
    export async function getSession() {
      const session = cookies().get("session")?.value;
      if (!session) return null;
      
      return session;
    }
    

    use

    //import getSession()
    export default async function RootLayout({
      children,
    }: Readonly<{
      children: React.ReactNode;
    }>) {
      const session = await getSession();
      return (
        <html lang="en">
          <body >
            <SessionProvider >
            <Toaster/>
            <RegisterModal/>
            <LoginModal/>
            <Layouts>
            {children}
            </Layouts>
            </SessionProvider>
            </body>
        </html>
    
    Login or Signup to reply.
  2. layout

    //import getSession()
    export default async function RootLayout({
      children,
    }: Readonly<{
      children: React.ReactNode;
    }>) {
      const session = await getSession();
      return (
        <html lang="en">
          <body >
            <SessionProvider session={session}>
            <Toaster/>
            <RegisterModal/>
            <LoginModal/>
            <Layouts>
            {children}
            </Layouts>
            </SessionProvider>
            </body>
        </html>
    

    context

    // SessionContext.tsx
    "use client";
    import React, { createContext, useContext, ReactNode, useState } from "react";
    
    interface SessionContextType {
      session: any;
    }
    
    const SessionContext = createContext<SessionContextType | undefined>(undefined);
    
    interface SessionProviderProps {
      session: any;
      children: ReactNode;
    }
    
    const SessionProvider: React.FC<SessionProviderProps> = ({ session, children }: SessionProviderProps) => {
      
      return (
        <SessionContext.Provider value={{ session }}>
          {children}
        </SessionContext.Provider>
      );
    };
    
    export const useSession = (): SessionContextType => {
      const context = useContext(SessionContext);
      if (!context) {
        throw new Error("useSession must be used within a SessionProvider");
      }
      return context;
    };
    
    export default SessionProvider;
    

    use in client component

    const {session} = useSession() 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search