How to solve NextJs Error: Failed to load / at loadComponents

Viewed 890

I initialized a NextJs app(v10.2.0) via npx create-next-app and replcaced below code in index.js file of the pages folder. I am trying to fetch data from a json file and then pass it as props to the page component.

import fs from 'fs/promises';
import path from 'path';

function Home(props) {
  const { products } = props;

  return (
    <ul>
      {products.map((product) => {
        return <li key={product.id}>{product.title}</li>;
      })}
    </ul>
  );
}


export async function getStaticProps() {

  const filePath = path.join(process.cwd(), 'data', 'products-data.json');
  const jsonData = await fs.readFile(filePath);
  const data = JSON.parse(jsonData);

  console.log(data);

  return {
    props: {
      products: data.products
    }
  };
}

export default Home;

And the products-data.json file is:

{
    "products": [{
            "id": "p1",
            "title": "Product 1"
        }, {
            "id": "p2",
            "title": "Product 2"
        },
        {
            "id": "p3",
            "title": "Product 3"
        }
    ]
}

But when i run the npm run dev, i get this error:

Error: Failed to load /
    at loadComponents (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/next-server/server/load-components.js:1:1554)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async DevServer.findPageComponents (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/next-server/server/next-server.js:76:257)
    at async DevServer.renderToHTML (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/next-server/server/next-server.js:137:542)
    at async DevServer.renderToHTML (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/server/next-dev-server.js:36:578)
    at async DevServer.render (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/next-server/server/next-server.js:74:255)
    at async Object.fn (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/next-server/server/next-server.js:58:672)
    at async Router.execute (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/next-server/server/router.js:25:67)
    at async DevServer.run (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/next-server/server/next-server.js:68:1042)
    at async DevServer.handleRequest (/home/ali/Desktop/NextJs3/nextjs3/node_modules/next/dist/next-server/server/next-server.js:32:504)

What is the problem with this code? is it because of importing core node modules?

1 Answers

Once I changed the promise based version of readFile() to readFileSync(), it worked :) Don't know why, but it works!

Parts of the code edited:

import fs from 'fs';
.
.
.
const jsonData = fs.readFileSync(filePath);
.
.
.

But couldn't figure out how to use the asynchronous version of readFile in this case.

Related