Next.js Discord

Discord Forum

What is the efficient way to pass data from a parent server component to a child server component?

Unanswered
Forest yellowjacket posted this in #help-forum
Open in Discord
Forest yellowjacketOP
I aim to efficiently pass data from the parent server component to the child server component. I comprehend the concept of deduping, but I'm uncertain about handling dynamic route since the params are accessible only to the base (parent) component and not the child component.

3 Replies

Forest yellowjacketOP
code sample

blog/[id]/page.tsx
import React from 'react'
import BlogBody from './BlogBody'

export interface Blog {
  userId: number
  id: number
  title: string
  body: string
}

export async function getBlog({ params }: { params: { id: string } }) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`, { cache: 'no-store' })
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data')
  }

  return res.json()
}

async function Blog({ params: { id = "0" } }: { params: { id: string } }) {
  const blog: Blog = await getBlog({ params: { id } })
  return (
    <div>
      <h1 className="text-5xl">{blog.title}</h1>
      <BlogBody />
    </div>
  )
}

export default Blog
BlogBody.tsx


import React from 'react'

async function BlogBody() {

  // TODO: How to fetch data like parent on nested level
  const blog = {}

  return (
    <>
      <pre>{JSON.stringify(blog, undefined, 2)}</pre>
    </>
  )
}

export default BlogBody
Forest yellowjacketOP
If you're encountering a similar issue, this GitHub discussion thread will provide you with the necessary assistance: https://github.com/vercel/next.js/discussions/53513