Next.js Discord

Discord Forum

How to fetch data once in server component

Unanswered
Forest bachac posted this in #help-forum
Open in Discord
Forest bachacOP
I'm trying to fetch some data on a server component and pass it to a client comonent at runtime but only once (cached when the user visits the site). Both the server component and client component wrap around the entire site. When I run "next build" the data fetching happens 17 times for all the static pages which are children of the server component.

Is there any way to fetch data from the server once at runtime and send it to the client component (at the root level of the site) without it running 17 times during build of the site?

4 Replies

European sprat
show code
@European sprat show code
Forest bachacOP
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {

  return (
    <html lang="en">   
        <head>
            <Analytics />
        </head>
      <body className={inter.className}>
      <a href="#main-content" className="skip-link">Skip to content</a>      

      <NavBar></NavBar>        

      <ServerPolicyCheck>              
              <main id="main-content">  
                {children}
              </main>       
      </ServerPolicyCheck>      

        <Footer />
      </body>
    </html>
  )
}


import 'server-only'

import Providers from "@/app/components/Providers";
import { cache } from 'react'

export const getPolicy = cache(async () => {
  //database call will go here
    console.log("Called getPolicy from server component");
    return true;
})
export default async function ServerPolicyCheck({ children }: any) {
    const testDBQuery = await getPolicy();
    return (
        <Providers hasAgreedToLatestPolicy={testDBQuery}>
            {children}
        </Providers>
    )
}


And then Providers is a client component that receives the prop hasAgreedToLatestPolicy.

Basically whenever someone visits a site, need to check with the database if they've agreed to the latest privacy policy and pass that down to the client component to conditionally render a modal pop up to agree or continue with the site.
On next build console.log("Called getPolicy from server component"); gets called 18 times
I just want it to run at runtime once with SSR and then cached