0

I'm trying to figure out why my getStaticProps is not sending any data. When I log the Home page props, it shows posts as undefined. I'm new to Next.js

Here's my code

export async function getStaticProps() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts/")
  const data = response.json()

  return {
    props: { data },
  }
}

export default function Home({ posts }: any) {
  console.log(`posts`, posts) // This prints undefined
  return (
    <main className="wrapper wrapper-aligned-center | flow">
      <h1 className="fz-900">Learning NextJS</h1>
    </main>
  )
}

Your help is greatly appreciated.

OMi Shah
  • 5,768
  • 3
  • 25
  • 34
Davina Leong
  • 737
  • 2
  • 11
  • 28
  • Can you show code how you have used `getStaticProps` function? – DecPK Sep 01 '23 at 05:54
  • Does this answer your question? [Getting props as undefined in component returned from getStaticProps](https://stackoverflow.com/questions/63434733/getting-props-as-undefined-in-component-returned-from-getstaticprops) – OMi Shah Sep 01 '23 at 06:06
  • Does this answer your question? [How to fetch data server-side in the latest Next.js? Tried getStaticProps but it's not running and getting undefined](https://stackoverflow.com/questions/76267351/how-to-fetch-data-server-side-in-the-latest-next-js-tried-getstaticprops-but-it) – Youssouf Oumar Sep 02 '23 at 06:14

2 Answers2

0

first of all there exsists two different options for

  • app router
  • page router

getStaticProps is only available in the old page router system, so be sure that you use the page router system if u wanna use getStaticProps

i am not sure, but the data you passed is not the data you read:

  • change data passing props: { posts: data },
  • or change data calling Home({ data }: any) and console.log(data, data)

as another tip, u can also stringify the object to check a specific object or the props at all, f.e. Home(props: any) and in your JSX return part <div>JSON.stringify(props, null, 2)</div>, maybe it will help you in future to debug problems in passing data

Stefan Schulz
  • 533
  • 3
  • 8
0

Ok, I found the answer while looking at the docs.

For app router, we don't use getStaticProps.

We just use a function to pull the data from the API and call it directly in the page like this:

export async function getData() {
  return connection.getData(connection.contentTypes.posts)
}

export default async function Home() {
  const posts = await getData()

  return (
    <main className="wrapper wrapper-aligned-center | flow">
      <h1 className="fz-900">Learning NextJS</h1>

      <h2 className="fz-700">Posts</h2>

      {posts.map(({ title, body }, index: any) => {
        return (
          <div className="flow" key={index}>
            <h3 className="fz-500 fw-bold tt-capitalize">{title}</h3>
            <p>{body}</p>
            <hr />
          </div>
        )
      })}
    </main>
  )
}
Davina Leong
  • 737
  • 2
  • 11
  • 28