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

Time:04-18

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?

CodePudding user response:

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>
  );
}
  • Related