Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting undefined when fetching a list of posts?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading