Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting undefined data while using getStaticProps() in next.js

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;
like image 377
Amjad Niazi Avatar asked Apr 14 '26 16:04

Amjad Niazi


1 Answers

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.

like image 101
Santeri Sarle Avatar answered Apr 17 '26 12:04

Santeri Sarle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!