1

im lerning to use next js while using the nextjs.org page guide

my question,

is that.
my getStaticProps function seems to get the data and logging correctly inside the get static props

but when i send the data ( with is the props object) i seem to get (undefined) error inside the component and loading the data

this is my getStaticProps function the all allPostsData variable is geting the data and passing it to props in the return keyword

export async function getStaticProps() {
  const allPostsData = getSortedPostsData();
  console.log("getStaticProps>>>",allPostsData)

  return {
    props: {
      allPostsData,
    },
  };
}

the log statement in here logs the correct data witch is this

getStaticProps>>> [
  {
    id: 'ssg-ssr',
    title: 'When to Use Static Generation v.s. Server-side Rendering',
    date: '2020-01-02'
  },
  {
    id: 'pre-rendering',
    title: 'Two Forms of Pre-rendering',
    date: '2020-01-01'
  }
]

but when i pass the props (witch is the allPostsData object) to the home component like this

export default function Home ({allPostsData })  {
  console.log("getStaticProps>>>",allPostsData)
}

i get undefined as if there was no data inside at all

i use

npm run dev 

to start the server although i don't think that is the problem

when trying to display the data using a .map method it shows nothing

example below

 {allPostsData && allPostsData.map
(({ id, date, title }) => 
({title }
 {date}
 {id}))}

1 Answers1

1

This is because getStaticProps is asynchronous in Next.js you need to add the await keyword. your console log may show the expected value because the promise has resolved and the data is available at that point. However, when you pass allPostsData as a prop to the Home component, the data is being passed as a pending promise if you don't use await, so it's not yet available and it need to be await before rendering the rest.

export async function getStaticProps() {
  const allPostsData = await getSortedPostsData();
  console.log("getStaticProps>>>",allPostsData)

  return {
    props: {
      allPostsData,
    },
  };
}
ShueiYang
  • 648
  • 1
  • 3
  • 7
  • i was using the guide provided here "https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops" i deleted the directory and and created another react app witch resolved the issue by it self im gone mark this answer as solved and thanks for the help brother – Mustafa sabah Jul 06 '23 at 17:50