I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be applied to arrays, while we are fetching an object from Strapi. How can I work around this issue? Additionally, in the tutorial at the 30-minute mark (link), the instructor uses the .map function even though "posts" is an object. How does that function correctly?
export default function Home({ posts }) {
return (
<div>
{posts &&
posts.map((post) => (
<div key={post.id}>
<p>{post.Title}</p>
</div>
))}
</div>
);
}
export async function getStaticProps() {
const res = await fetch("http://localhost:1337/api/posts");
const posts = await res.json();
return {
props: { posts },
};
}
UPDATE: I managed to solve the problem by writing the following code:
export default function Home({ posts }) {
return (
<div>
{posts &&
posts.data.map((post) => (
<div key={post.attributes.id}>
<p>{post.attributes.Title}</p>
<p>hello there</p>
</div>
))}
</div>
);
}
export async function getStaticProps() {
const res = await fetch("http://localhost:1337/api/posts");
const posts = await res.json();
return {
props: { posts },
};
}
The JSON data I wanted to access was located under the 'data' and 'attributes' properties.