Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strapi v4 api error "posts.map is not a function" NextJs

index.js file

export default function Home({ posts }) {
  return (
    <div>
      {posts &&
        posts.map((post) => (
          <div key={post.id}>
            <h2>{post.Title}</h2>
          </div>
        ))}
    </div>
  );
}

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/api/posts");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

and this is the error that appears to me "TypeError: posts.map is not a function"
Any idea about it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

posts is an object — the array of posts you want to call map on is assigned to posts.data:

export default function Home({ posts }) {
  const { data } = posts; // unpack `data` from `posts`

  // call `map()` on `data`
  return (
    <div>
      {data && data.length
        ? data.map((post) => (
            <div key={post.id}>
              <h2>{post.attributes.Title}</h2>
            </div>
          ))
        : "no posts"}
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading