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.
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>
)
}