Angga Ari Wijaya
Angga Ari Wijaya

Reputation: 1811

Next.js 13 render server component inside client component page

I build a simple landing page with next.js 13 with app router. I use useRef to create a "jump to section" effect by clicking menu from header to content of the page, but the section of the page fetch data from database directly with prisma (not using fetch to external api)

page.tsx

"use client"
export default function Home() {
    const homeRef = useRef<HTMLElement>(null);
    const aboutRef = useRef<HTMLElement>(null);
    return (
      <>
         <Header sections={[homeRef, aboutRef]}/>
         <main className="main">
             <Home ref={homeRef}/>
             <About ref={aboutRef}/>
         </main>
      </>
    )
}

about.tsx

export const About= forwardRef(async (props, ref: ForwardedRef<HTMLElement>) => {
    const about = await getAbout(); // fetching from database directly with prisma
    return (
        <section className="section" id="about" ref={ref}>
            <h1 className="section__title">About</h1>

            <p>{about.description}</p>
            <p>{about.last_updated_at}</p>
        </section>
    );
});
Expertise.displayName = 'About';

but I got error from prisma

Uncaught (in promise) Error: PrismaClient is unable to run in this browser environment, or has been bundled for the browser (running in `unknown`).

and nextjs itself

Error: async/await is not yet supported in Client Components, only Server Components.

I read in docs and some references that Server components can import and render client components, but client components can't render the server components in it.

But I still need useRef and fetch data from database, how rendering strategy and compose the component that I can use to achieve that.

Upvotes: 0

Views: 1983

Answers (1)

Khoa
Khoa

Reputation: 2932

Solution 1

If getting "about" data at server is not a must, you can let your About component to be "client component".

Next, instead of calling await getAbout() directly, you can create an API route with GET method.

Finally, let your client About component handle remote data fetching (url will be the API route above) with library like Redux toolkit or tRPC or even build your own a simple solution for remote data fetching (with for basic states: init, fetching, success, failure).

Solution 2

If getting "about" data at server is a must:

Upvotes: 0

Related Questions