skip to Main Content

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


  1. getStaticProps only runs on the pages.

    getStaticProps can only be exported from a page. You cannot export it
    from non-page files, _app, _document, or _error.

    One of the reasons for this restriction is that React needs to have
    all the required data before the page is rendered.

    you could use it inside PostsPage and pass it to ListOfPosts as prop.

    if it is in app directory, those server side functions do not run on app directory. it only runs on pages directory.

    Login or Signup to reply.
  2. 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:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search