Search code examples
node.jsnext.jsfetch

Error: Failed to collect page data from /blog/[id]


const Details = ({ userData }) => {
  return (
    <Layout>
      <h1>{userData?.header}</h1>
    </Layout>
   )
}

export default Details

 
export const getStaticPaths = async () =>{
  const res = await fetch(`http://localhost:3000/api/blogs`);
  const blogs = await res.json();
  const ids = blogs.map((blog) => blog.id);
  const paths = ids.map((id)=> ({params:{id: id.toString()}}));

  return{
    paths,
    fallback:false,
  };
};

export const getStaticProps = async (context) =>{
  const res = await fetch(`http://localhost:3000/api/blogs/${context.params.id}`);
  const userData = await res.json();

  return{
    props:{
      data,
      userData,
    }
  }
}

While npm run build my Next.js project, I am getting such an error in the console:

Error: Failed to collect page data from /blog/[id]

Why does this happen?


Solution

  • Because of you are not fetching anything from any Api, you don't need to fetch anything remotly. That's why you are getting an ECONNREFUSED error.

    Update

    I've found two errors in your /blog/* folder:

    • Add - 1 in line 106 of /blog/[id].js (See bellow)
    • Remove lines 131 and 132 of /blog/index.js

    /blog/[id].js

    import { data } from "../../data.js";
    
    const Details = ({ userData }) => {
      return <Layout>{/* ... */}</Layout>;
    };
    
    export default Details;
    
    export const getStaticPaths = async () => {
      const ids = data.map(({ id }) => id);
      const paths = ids.map((id) => ({ params: { id: id.toString() } }));
      return {
        paths,
        fallback: false,
      };
    };
    
    export const getStaticProps = async (context) => {
      // You where trying here to get posts by id:
      // 1, 2, 3, 4
      // But what you really want is to get array indexes:
      // 0, 1, 2, 3
      // that's why we are adding - 1
      const userData = data[context.params.id - 1]; // <----- add - 1
    
      return {
        props: {
          data,
          userData,
        },
      };
    };
    

    /blog/index.js

    export const getStaticProps = async (context) => {
      // ----- remove the fetch -----
    
      return {
        props: {
          data,
        },
      };
    };