3

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;

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Agreed. Even if was allowed, getting data in the component is not good practice. The component should handle its implementation and data should be passed to it for handling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.