'Strapi v4 api error "posts.map is not a function" NextJs
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?
Solution 1:[1]
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>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
