NextJS: When attempting to serialize the `function` as JSON, an error occurs as it is not a JSON serializable data type

In my Firestore database, I have a collection named "mentor" that contains documents with three fields: "name", "email", and "linkedin". My goal is to fetch all the documents from this collection and pass them as props so that I can render their fields on my page.

To achieve this, I am using getServerSideProps to retrieve the Firestore data before rendering the page. Below is my code snippet:

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: {} };
    }
  }

Unfortunately, I encountered an error while trying to serialize the data returned from `getServerSideProps`. The specific issue relates to attempting to serialize a `function`, which is not permissible for JSON serialization. Can anyone advise on how to address this? Apologies for any errors in the code provided, as I am still learning JavaScript.

Answer №1

doc.data should be treated as a function, not raw document information. Refer to the official API documentation for better understanding. It is recommended to invoke this function to retrieve an object containing the snapshot data.

instructors.push({instructorID: doc.id, instructorData: doc.data()})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to retrieve information from the prefetch function and use it as an argument for another prefetch function in React-query?

In simple terms, I have a situation where I need to retrieve some data first and then use that data to fetch additional information. The catch is that I need an ID value from the initial data in order to do so. My entire page is statically generated (SSG ...

What are the differences between incorporating JavaScript directly into HTML and writing it in a separate file?

I need help converting this JavaScript embedded in HTML code into a standalone JavaScript file. I am creating a toggle switch that, when clicked, should go to a new page after the transformation. I am looking for the non-embedded version of the function. H ...

Transitioning from AngularJS to Angular 2: Exploring Alternatives to $rootScope.$on

Our journey with the AngularJS project has begun on the path towards the modern Angular. The ngMigration utility advised me to eliminate all dependencies on $rootScope since Angular does not have a concept similar to $rootScope. While this is straightforw ...

Tips for conducting a simultaneous test on several devices

Struggling to execute a single test script on multiple devices, regardless of efforts. There is one test apk and script obtained from a website as a sample. The script locates a textbox in the application, enters "Hello World!" into it, then completes the ...

Tips for successfully passing multiple properties to a function in React

<DeleteForeverIcon className={classes.deleteHwIcon} onClick={() => { deleteHomework(value.name, value.class); }} /> I'm looking to modify the function deleteHomework so that it can receive two properties instead of just one. In add ...

Revalidating doesn't seem to work as expected in Next JS

Reviewing my code on the development server function Home(props) { console.log("Hello") return ( <ul> {props.user.map((user) => ( <li key={user.id}>{user.email}</li> ))} </ul> ) } expo ...

What is the best way to locate an element through its parent?

I am working with the following HTML structure: <div class="row" id="row-1"> <div class="row-wrapper"> <div class="cell-1"></div> <div class="cell-2"></div> <div class="cell-3"></div> ...

The hierarchical structure in the DOM that mirrors an HTML table

While working on code to navigate the DOM for a table, I encountered an unexpected surprise. The DOM (specifically in FF) did not align with my initial expectations. Upon investigation, it appears that FF has automatically inserted a tbody along with sever ...

Determine the coordinates of the mouse cursor within a specific div element

Similar Questions: Determining Mouse Position Relative to a Div Getting the Mouse Position Using JavaScript in Canvas Is there a way to retrieve the mouse position within a canvas element with fixed dimensions and automatic margin? I am unable to ...

Troubleshooting 404 Error When Using Axios Put Request in Vue.js

I'm trying to update the status of an order using Axios and the Woocommerce REST API, but I keep getting a 404 error. Here's my first attempt: axios.put('https://staging/wp-json/wc/v3/orders/1977?consumer_key=123&consumer_secret=456&apos ...

Insufficient Resources Error (net::ERR_INSUFFICIENT_RESOURCES) encountered while executing jQuery script with multiple ajax requests for 2 minutes

Upon initially loading the code below, everything seems to be functioning smoothly with the dayofweek and hourofday functions. However, shortly thereafter, the browser (Chrome) freezes up and displays the error message: net::ERR_INSUFFICIENT_RESOURCES. Thi ...

Focused on individual characters in a string to implement diverse CSS styles

Is there a way I can apply different CSS classes to specific indexes within a string? For example, consider this string: "Tip. \n Please search using a third character. \n Or use a wildcard." I know how to target the first line with CSS using : ...

Leverage the power of react-i18next in class-based components by utilizing decorators and Higher Order

Currently, I am working on implementing i18n into my React project that also utilizes Redux, with the assistance of react-i18next. In this particular project, we are using class components alongside decorators. Originally, I intended to experiment with r ...

Is it possible to save or write a text file in the VueJs renderer process without the need to open the dialog box?

Currently, I am working on a project using VueJs + electron, where I need to save a text file to the user's PC without any prompt or dialog box popping up. I am aware of how to do this using require('fs'), but unfortunately fs does not work ...

Altering content using jQuery

Trying to create a dynamic quiz using HTML, CSS, and jQuery. I am having trouble changing the <p id=question></P> element with jQuery code as nothing happens. Below is my HTML and jQuery code: <!DOCTYPE html> <html lang='es' ...

Vuetify - Implementing a search feature in a table that automatically navigates to the matching row

Currently, I am working with 2 Vuetify data tables that do not have pagination enabled. Each row in the second table corresponds to exactly one parent in the first table. My goal is to be able to click on an entry in the second table and have it automati ...

Create a server directory structure that populates multiple HTML dropdown lists using either jQuery or AJAX

As a novice navigating jQuery and Ajax, I find myself faced with a specific challenge. My current situation involves a structured set of directories on a server. My goal is to populate a dropdown dynamically with this file hierarchy. Upon click ...

Limiting page entry with passport.js and express middleware

My server is set up to authenticate user login. I have successfully redirected users to the success page after authentication (and back to the login page if it fails). However, I am facing an issue with using my own express middleware to restrict access fo ...

Accessing a Kendo Grid instance within an Angular directive

Continuing from the previous question, which can be found here, I have an additional query that I felt warranted a separate post. The link provided above demonstrates how to obtain a grid instance in Angular, credit to Lars for that. Building upon the ex ...

"Encountered an issue with the pnpm command not being found while executing a script through GitHub Actions, however, it ran successfully

I am in the process of automating my Next.js deployment and creating a deploy.sh script to execute on the server using GitHub Actions. When I manually run it on the server with the bash deploy.sh command, everything works smoothly. However, when I try to r ...