skip to Main Content

I want share any data for each request, so I create object with these data in rootLayout

export interface IProps {
    children: React.ReactNode;
    data: any;
}

export default function RootLayout(props: IProps) {
    const {children} = props;
    props.data = {item: "hello"} // I know this is bad (only for test)
    return children;
}

Now I need access data in page or layout on server side.

export default function Layout(props: IProps) {
    const {children, data} = props;
    console.log("Data", data);
    return children;
}

Is there any way for share data per request or can I extend props for all children of root layout (on server)?

2

Answers


  1. Chosen as BEST ANSWER

    Okey here is exactly my issue:

    RootLayout.tsx (create instance per request)

    export interface IProps {
        children: ReactNode;
        data: {
            nodeInstance: InstancePerRequest;
        }
    }
    
    export default function RootLayout(props: IProps) {
        const {children} = props;
        props.data.nodeInstance = new InstancePerRequest();
        return children;
    }
    

    layout.tsx (child server component)

    export default function LocaleLayout(props: IProps) {
        const { children, data} = props;
    
        data.nodeInstance.doSomething();
    
        return (
            <html>
                <body className={styles.globalWrap}>{children}</body>
            </html>
        );
    }
    

    page.tsx

    const Page = (props: IProps) => {
        props.data.nodeInstance.getSomething();
        return <div>Empty</div>
    }
    
    export default Page
    

    All of these usages of nodeInstance has one instance per request. But this solution doesnt work.


  2. answered here:

    also if you want to share data between server components base on nextjs document you can call your api with fetch anywhere you want:

    Instead of using React Context (which is not available on the server)
    or passing data as props, you can use fetch or React’s cache function
    to fetch the same data in the components that need it, without
    worrying about making duplicate requests for the same data. This is
    because React extends fetch to automatically memoize data requests,
    and the cache function can be used when fetch is not available.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search