An issue occurred when retrieving data from Firebase using Next.js, where a null value was returned

I am facing an issue with my NextJS app where I have integrated both Stripe for payment functionality and Firebase for database storage. The user data is successfully stored in Firebase with all the required values, but when trying to fetch it to display on the orders page, I am getting an empty array. The query to fetch the data seems to be successful, however, the data array returned is null.

MY ORDERS PAGE

import Navbar from "@/Components/Navbar";
import React from "react";
import { useSession, getSession } from "next-auth/react";
import { moment } from "moment";
import db from "../../firebase";
import Orderr from "@/Components/Orderr";

function Orders({ orders }) {
  const { data: session } = useSession();
  console.log(orders);
  return (
    <div>
      <Navbar />
      <main className="max-w-screen-lg mx-auto p-10">
        <h1 className="border-b mb-2 pb-1 ">Your Orders</h1>
        {session ? (
          <h2>{orders ? orders.length : 0} orders</h2>
        ) : (
          <h2>Please sign in to see your orders</h2>
        )}
        <div>
          {orders?.map(({ id, amount, items, timestamp, images }) => (
            <Orderr
              key={id}
              id={id}
              amount={amount}
              items={items}
              timestamp={timestamp}
              images={images}
            />
          ))}
        </div>
      </main>
    </div>
  );
}

export default Orders;

export async function getServerSideProps(context) {
  const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
  const session = await getSession(context);
  if (!session) {
    return {
      props: {},
    };
  }
 
  const stripeOrders = await db
    .collection("users")
    .doc(session.user.email)
    .collection("orders")
    .orderBy("timestamp", "desc")
    .get();

  console.log(stripeOrders);
  const orders = await Promise.all(
    stripeOrders.docs.map(async (order) => ({
      id: order.id,
      amount: order.data().amount,
      images: order.data().images,
      timestamp: moment(order.data().timestamp.toDate()).unix(),
      items: (
        await stripe.checkout.sessions.listLineItems(order.id, {
          limit: 100,
        })
      ).data,
    }))
  );

  console.log(orders);
  return {
    props: {
      orders,
    },
  };
}

Firebase.js

import firebase from "firebase/compat/app";
import "firebase/compat/firestore";

const firebaseConfig = {
  apiKey: "AIzaSyBpb1-3U22I3ajHcTFoUnwIAajzRu64KNo",
  authDomain: "meraki-corner.firebaseapp.com",
  projectId: "meraki-corner",
  storageBucket: "meraki-corner.appspot.com",
  messagingSenderId: "384440845152",
  appId: "1:384440845152:web:92ce7ab8428ac30c029405",
};

const app = !firebase.apps.length
  ? firebase.initializeApp(firebaseConfig)
  : firebase.app();

const db = app.firestore();
export default db;

Answer №1

employ a constant session variable and wait for the getSession() function to resolve.

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

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

Sorting through mongoose information on the front end using EJS depending on a dropdown pick

Beginner embarking on my inaugural project here. I have developed 2 Mongoose schematics and models for managing categories and products. The products are nested within the corresponding categories model. Using Node and Express, I successfully sent all ca ...

Unable to load templateUrl when constructing a custom directive

Currently, I am delving into the world of directives as they appear to be quite advantageous. My intention was to implement a directive for a top navigation bar. However, I find myself perplexed as the templateUrl fails to load. Despite scouring through va ...

Step-by-step guide on removing the focusin event listener from a Bootstrap 5 modal

My current app has a legacy modal that uses a kendo dropdown list element bound to an ajax call with filtering. I'm trying to avoid rewriting this component if possible. However, there is an issue where when the modal opens and you focus on the dropdo ...

Does ExpressJS always terminate with JSON by default?

I am currently utilizing expressjs to serve JSON data. Upon attempting to use res.end() with an object, I encounter the following error: TypeError: first argument must be a string, Array, or Buffer Is there a specific setting or middleware available tha ...

Customizing button appearances in the control div on Google Maps - A guide

Is there a way to manipulate elements and adjust styles by clicking buttons on the map control div? I want to achieve the same effect on the map as with the buttons in the table. Code: jsFiddle Update: Thanks to your assistance, I was able to achieve th ...

What is the best way to structure my protractor scenarios for effectively validating HTTP response errors?

My current setup involves using protractor to test the functionality of my Angular client, while the server is implemented using Python Google App Engine. In order to enhance my protractor test, I am looking to include an assertion on the http response ge ...

Using Node.js, securely encode data using a private key into a base64 format that can only be decoded on the server side

Here is my specific situation: An http request arrives at the server for a login action A user token needs to be created. This token consists of a Json object composed of different fields. It is then converted to a string and encoded in Base64. const ...

Issue: [$injector:unpr] encountered while configuring routing

Looking to implement a basic authentication system for my angularjs application. The problem arises when I try to debug the app.js on line 20, and an error is displayed: Error: [$injector:unpr] http://errors.angularjs.org/1.2.16/$injector/unpr?p0=configPr ...

Struggling to generate a user using the supabase.auth.admin.createUser() function, encountering the error "Failed to create new user due to database error"

While working on my Next.js project, I encountered an issue when trying to create a user using the supabase.auth.admin.createUser() method. The error message I received was: { message: "Database error creating new user" name: "AuthApiE ...

Exploring the distinctions in e2e testing for select (dropdown), input radio, and input checkbox elements within AngularJS

In AngularJS, testing form attributes can be a bit inconsistent. While the updated e2e testing with Protractor helps, those still using older versions may struggle. I am interested in understanding the differences between: Ways to select items: 1a. Selec ...

Error in table layout caused by asynchronous .get jQuery function

I am facing a challenge in populating a timetable with specific information for each cell from a database. The table is being dynamically refreshed using the following function: function refreshTable() { //Form values var park = $('#Park&apos ...

Creating a tooltip for a specific cell within an AG grid react component is a useful customization feature

How can I customize the tooltip for a specific row in my AG Grid? I see that there is a tooltipField available in ColDefs, but I want to provide a custom string instead of using a field value. Is there a way to achieve this customization? ...

jquery activating the toggle function to switch between child elements

I'm facing a challenge where I can't use .children() in this scenario, as it won't work since the elements aren't technically children. Here's the snippet of HTML that I'm working with: <p class="l1">A</p> ...

Encountering a problem with Selenium when dealing with tabular data displayed in a DIV format on a website, where each row is encapsulated within its own DIV element

While creating Selenium automation tests for a website with multiple rows contained within a main DIV element, each row represented by a separate DIV. For example, if there are 5 dynamically generated rows, the HTML code structure would look like this: < ...

Received an error while attempting to install react-router-dom

I keep encountering this error message whenever I try to install react-router-dom using NPM in VS Code: https://i.sstatic.net/hFshb.png npm ERR! Unexpected end of JSON input while parsing near '...stack-launcher":"^1.0' npm ERR! You can find ...

Verify whether a variable includes the tag name "img."

Currently, I am working with a variable that holds user input in HTML format. This input may consist of either plain text or an image. I am looking to determine whether the user has entered an image or just simple text. Here is an example of user entry: t ...

Utilizing Bootstrap 5 for Angular Projects

With the release of version 5, the Bootstrap framework has eliminated the need for jQuery. I am curious about how this change impacts Angular applications. Can we still utilize all of Bootstrap's features in Angular, such as dropdowns? In the past, ...

Issue with inserting ContentPlaceHolder in script tags

In my ASP.Net Master Page, I encountered an issue: <script language="javascript" type="text/javascript"> <asp:ContentPlaceHolder ID="scriptContentHolder" runat="server"></asp:ContentPlaceHolder> </script> When attempt ...

Jquery animation is dragging its feet on Explorer, while other browsers are zipping along

Hey everyone, I am facing an issue with a simple jquery plugin I created for an animated menu. You can check out the entire site here: Main website My Library the "bootstrap" file The problem is that the red rectangle animates smoothly in Firefox, Op ...