Search code examples
next.jsstrapi

Next.JS: TypeError: Cannot read properties of undefined (reading "map")


Im trying to make an blog with NextJs and Strapi. When I get the posts with getStaticProps I always get this error when mapping.

Heres my code:

  export default function Home({ posts }: { posts: any }) {
  console.log(posts);

  return (
    <>
      <Head>
        <title>Blog</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        {posts &&
          posts.map((post: any, i: number) => {
            return (
              <div key={i}>
                <h3>{post.attributtes.Title}</h3>
                <h5>{post.attributtes.H2}</h5>
                <p>{post.attributtes.Description}</p>
              </div>
            );
          })}
      </main>
    </>
  );
}

export async function getStaticProps() {
  const res = await axios({
    method: "get",
    url: "http://0.0.0.0:1337/api/posts",
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Content-type": "application/json",
      "Access-Control-Allow-Methods": "POST, GET, PUT, DELETE, OPTIONS",
      "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token",
    },
  });
  const data = res.data;

  return {
    props: {
      posts: data.data,
    },
  };
}

It gives me this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'Title')

But when I check it on console.log its not undefined:

console.log(posts)

Im trying very hard but I dont know what can be happening here. Could anyone help?


Solution

  • There's a typo which is why that field cannot be accessed.

    <h3>{post.attributtes.Title}</h3>
                      ^