Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda