getInitialProps() should resolve to an object. But found “undefined” instead

Total
1
Shares

I’m trying to fetch data from firebase to my next.js application using getInitialProps but the data shows up in the VS Code terminal (along with some errors). However, in the browser, I get this message

getInitialProps() should resolve to an object. But found "undefined" instead

Please check the code

// Other import code
import { firestore } from "../firebase/firebase.utils";

const Hotels = (props) => {
  return (
    // jsx code
  );
};

Hotels.getInitialProps = async (ctx) => {
  let hotelsRef = firestore.collection("hotels");
  let query = hotelsRef
    .get()
    .then((snapshot) => {
      if (snapshot.empty) {
        console.log("No matching documents.");
        return;
      }

      snapshot.forEach((doc) => {
        console.log(doc.id, "=>", doc.data());
        return { props: doc.data() };
      });
    })
    .catch((err) => {
      console.log("Error getting documents", err);
    });
};

export default Hotels;

Any help is appreciated.


Solution

I think you should return from object from getInitialProps , but in your case you are not returning anything and also not making any use of async await

Here you go :

Hotels.getInitialProps = async (ctx) => {
    let hotelsRef = firestore.collection("hotels");
    let snapshot = await hotelsRef.get()
    if (snapshot.empty) {
        console.log("No matching documents.");
        return;
    }
    let data = []
    snapshot.forEach((doc) => {
        console.log(doc.id, "=>", doc.data());
        data.push(doc.data());
    });
    return { props : data };
};

Leave a Reply

Your email address will not be published. Required fields are marked *