Home  >  Q&A  >  body text

How to pass data obtained asynchronously via getServerSideProps to a component in Next.js?

Thank you for participating in the question! I'm still learning and may need you to explain it to me like a 5 year old.

Great places to work:

On my home page, I'm getting the data from getServerSideProps and mapping it. The data is obtained from data.json in the project folder.

Export default function Homepage({ data }) { ... }

Export asynchronous function getServerSideProps() { ... }

Homepage has mapping function 1... This works fine for me!

What do I want to do:

Now, I want to access the data obtained by getServerSideProps() from inside the component named ListComponent.

I want to use the original data again in mapping function 2. I want this to happen inside the ListComponent.

The ListComponent will then be imported into my home page.

What doesn’t work:

Inside the ListComponent I try to pass in the same data that I use on the homepage, like this:

Export default function ListComponent({ data }) { ... }

But it didn't work. It says data is undefined or data cannot be read. Why is this happening? How do I pass data to ListComponent?

P粉511749537P粉511749537426 days ago511

reply all(1)I'll reply

  • P粉006847750

    P粉0068477502023-09-12 10:42:39

    You just need to pass the data as props:

    export default function Homepage({ data }) {
      return (
       // ...
       <ListComponent data={data} />
       // ...
      )
    }

    Now, you have props named data:

    export default function ListComponent({ data }) { 
      // 使用数据
    }

    reply
    0
  • Cancelreply