I am following a YouTube tutorial on how to make a simple blog using Next.js and Strapi. Below is the code for fetching post data from Strapi. It does not work because the .map function used in the Home function can only be used on arrays. I am fetching an object from Strapi. How do I get around this? And also, if you view the YouTube tutorial that I am following (link), at the 30 minutes mark, you can see that the person is using the .map function even though "posts" is an object. How does that work?
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 was able to find out the solution to 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 that I was trying to access was under data and attributes.