Advertisements
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?
>Solution :
You don’t need the getStaticProps
function in the /app
directory.
async function getData() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
// Recommendation: handle errors
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return <main>{JSON.stringify(data, null, 2)}</main>
}
Further readings: