I am trying to fetch a list of posts form jsonplaceholder with nextjs and axios.
This is my ListOfPosts.jsx
import Link from "next/link";
import axios from "axios";
export default function ListOfPosts({posts}) {
return(
<div>
{posts.map(post => (
<div key={post.id}>
<Link href={`/posts/${post.id}`}>{post.body}</Link>
</div>
))}
</div>
)
}
export const getStaticProps = async () => {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
console.log(response.data);
const posts = response.data;
return {
props: {
posts
}
}
}
And this is my posts/page.jsx
import ListOfPosts from "./ListOfPosts";
export default async function PostsPage({posts}) {
return (
<>
<section>
<ListOfPosts posts={posts}/>
</section>
</>
)
}
The error i am getting is cannot read properties of undefined (reading 'map')
at ListOfPosts.jsx
What am i doing wrong when trying to fetch posts with axios?
2
Answers
getStaticProps only runs on the pages.
you could use it inside
PostsPage
and pass it toListOfPosts
as prop.if it is in app directory, those server side functions do not run on
app
directory. it only runs onpages
directory.You don’t need the
getStaticProps
function in the/app
directory.Further readings:
JSON.stringify() usually null?