Reputation: 53
I created a project starting from create-next-app.
Inside the Blog.js page I tried to fetch from https://jsonplaceholder.typicode.com/posts using the getStaticProps()
function.
I used the guide https://nextjs.org/docs/basic-features/data-fetching/get-static-props#using-getstaticprops-to-fetch-data-from-a-cms. Once everything is implemented, I open the page in the browser and it tells me
Server Error
TypeError: Cannot read properties of undefined (reading 'map')
Here is the code
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
export default Blog
Upvotes: 5
Views: 5905
Reputation: 56
You are writing the function inside of the component you want to render. The only situation you are going to do this is when you are making dynamic URLs based on some parameter, in that case you will use getStaticProps and getStaticPages mixed.
Try to do something like this:
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}
export default Blog
import type { NextPage } from "next";
import Blog from 'wherever it is'
const Home: NextPage = ({posts}) => {
return (
<>
<Blog posts={posts}/>
</>
);
};
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
export default Home;
P.S. When you are using map, never forget the key property
Upvotes: 2
Reputation: 1
I think the answer is you implement the Blog component outside of the Page folder.
Upvotes: 0