Search code examples
next.jsasync-awaitcomponentsserver-side-rendering

share data between serve side components


Can I make this more efficient without having to do two call to getPosts ? I want to use the initial posts to create different layout but i dont want to keep using getPosts() or is that juts not possible ?

import { getPosts } from "../../sanity-utils"
 
 
 export default async function Server() {
    const posts = await getPosts();
  
    return (
        <div className="">
        {posts.map((post) => (
          <div key={post.id } className="">
            <h1>{post.title}</h1>
            <img src={post.image} alt="image"  className="w-1/3 "/>
          </div>
        ))}
        </div>
    );
  }
 export async function Card() {
    const posts = await getPosts();

    return (
        <div className="">
        {posts.map((post) => (
          <div key={post.id } className="flex">
            <h1>{post.title}</h1>
            <img src={post.image} alt="image"  className="w-1/3 "/>
          </div>
        ))}
        </div>
    );
}

Solution

  • The way you are doing it is actually the preferred method currently when using Next.js. Next will automatically batch and cache the fetch requests as appropriate (can be overridden) so that you are not making unnecessary calls to the server for the same data. You should fetch your data where it is being consumed, and generally allow Next to handle the rest.

    Here is a Relevant excerpt from the documentation on the subject, that applies equally well to your situation:

    Good to know: For layouts, it's not possible to pass data between a parent layout and its children components. We recommend fetching data directly inside the layout that needs it, even if you're requesting the same data multiple times in a route. Behind the scenes, React and Next.js will cache and dedupe requests to avoid the same data being fetched more than once.