1

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?

2
  • If you console.log(posts) in your getStaticProps() function, can you confirm that it's an array? Commented Apr 17, 2022 at 19:16
  • oh nooo it's not this is what it shows me { data: [ { id: 1, attributes: [Object] }, { id: 2, attributes: [Object] }, { id: 3, attributes: [Object] }, { id: 4, attributes: [Object] } ], meta: { pagination: { page: 1, pageSize: 25, pageCount: 1, total: 4 } } } Commented Apr 17, 2022 at 19:19

1 Answer 1

2

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>
  );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Yea and how can I access the Title please?
This is the stracture { "data": [ { "id": 1, "attributes": { "Title": "Hello everyone", "Slug": "hello-everyone", "Content": "HSASUAKDQVFVJQVFVFQJFB", "createdAt": "2022-04-17T17:51:20.265Z", "updatedAt": "2022-04-17T17:51:22.528Z", "publishedAt": "2022-04-17T17:51:22.524Z" } }, }
@YacineAyechi You'd access it by using post.attributes.Title. Please see updated answer.
Yes, thanks for you help <3

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.