Reputation: 147
I am getting Cannot read property 'map' of undefined when using getStaticProps in next.js inside components/featured-posts.js but if i use it directly on pages/index.js page it shows the results, anybody know why its doing this?
export async function getStaticProps(){
const data = await fetch('http://localhost/newblog/newblogapi/posts')
const posts=await data.json();
return {
props: { posts }, // will be passed to the page component as props
}
}
const FeaturedPosts = ({posts}) => {
console.log(posts)
return (
<div className="album py-5 bg-light">
<div className="container mt-5">
{ posts.map(post=>(
<div key={post.id}>
<h3>{post.title}</h3>
</div>
))}
</div>
</div>
);
}
export default FeaturedPosts;
Upvotes: 3
Views: 1248
Reputation: 1001
You can only use getStaticProps on pages (files in the /pages directory), not in regular React components. I suggest you get the posts in your pages/index.js file and pass them as props to the FeaturedPosts component.
Upvotes: 3