mukunda
mukunda

Reputation: 685

NextJS: `function` cannot be serialized as JSON. Please only return JSON serializable data types

I have a Firestore collection by the name of "mentor". Each document in the collection contains three fields: "name", "email" and "linkedin".

I want to fetch all the documents in the collection and pass them as props. I want to then access these document fields to be rendered on my page.

I am using getServerSideProps to fetch the Firestore data prior to rendering the page. My code is as follows:

dashboard.js:

import nookies from "nookies";
import { onSnapshot, getFirestore, collection, getDocs } from "firebase/firestore";

export default function dashboard({session,mentors}){
       return(
            //rendering each value in the mentors array
          )
}

export async function getServerSideProps(context) {
    try {
      const cookies = nookies.get(context);
      const token = await verifyIdToken(cookies.token);
      if (!token) {
        return {
          redirect: {
            permanent: false,
            destination: "/login",
          },
          props: {},
        };
      }
      const mentors = [];
      const db = getFirestore();
      const querySnapshot = await getDocs(collection(db, "mentor"));
        querySnapshot.forEach((doc) => {
            mentors.push({mentorID: doc.id, mentorData: doc.data})
          });
      return {
        props: {
          session: token,
          mentors,
        },
      };
    } catch (error) {
      context.res.writeHead(302, { location: "/login" });
      context.res.end();
      return { props: {} };
    }
  }

However, I am getting the following error in the console:

error - Error: Error serializing `.mentors[0].mentorData` returned from `getServerSideProps` in "/dashboard".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.

How do I fix this? Please excuse me if there is some error in the code. I am relatively new to JS.

Upvotes: 0

Views: 2665

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317808

doc.data is a function, not actual document data. See the API documentation for clarity. You should instead call it in order to get an object with the data in the snapshot.

mentors.push({mentorID: doc.id, mentorData: doc.data()})

Upvotes: 1

Related Questions