简体   繁体   中英

getServerSideProps does not fetch the data at first time in Nextjs

I have a component that fetch data from my MongoDB database.After fetching the data, I want to create some cards by this data. My backend server is working. Also I connect my frontend to backend.

import axios from "axios";
import Cards from "../components/Cards";
import CarouselComponent from "../components/Carousel";
import { Navbar } from "../components/Navbar";

export default function Home({ products }) {
  console.log(products);
  return (
    <div className="">
      <Navbar />
      <CarouselComponent />
      {/* <Cards products={products} /> */}
    </div>
  );
}

export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`http://localhost:3000/api/products`);
  const data = await res.json();

  // Pass data to the page via props
  return { props: { products: data } };
}


在此处输入图像描述 products prop is turns me empty object. But when I refresh the page second time, it brings me all the products. I tested it in postman, also in postman I can get all the products. Why when I stop the server and start it again it doesn't fetch the products?

SOLUTION I added

 await dbConnect();

to

export async function getServerSideProps() {
  // Fetch data from external API
  await dbConnect();
  const res = await fetch(`http://localhost:3000/api/products`);
  const data = await res.json();

  // Pass data to the page via props
  return { props: { products: data } };
}

I think my mistake was to try fetching data before connecting to server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM