getStaticProps not sending data to page in Next.js

53 Views Asked by At

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.

2

There are 2 best solutions below

0
Davina Leong On BEST ANSWER

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>
  )
}
1
Stefan Schulz On

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