Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 } };
}


enter image description here 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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda