Error encountered when auto-generating IDs in Next.js with Firebase Firestore database

Hello, I am trying to access the details of my page in Next.js and retrieve data from a Firestore database. Here is the error message I am encountering:

Firebase initialized successfully page.js:32 router.query: undefined page.js:34 Movie ID: undefined page.js:47 Error fetching movie details: FirebaseError: Function doc() cannot be called with an empty path.

Any idea why this is happening? PS: The URL is correct

http://localhost:3000/movie/Mp9MwJPtaqko3foU95CE => Mp9MwJPtaqko3foU95CE is the auto-generated ID in the database

"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { getFirestore, collection, doc } from "firebase/firestore";
import { initializeApp } from "firebase/app";

import firebaseConfig from "../../firebaseConfig";

const MovieDetail = () => {
  const router = useRouter();
  const [movieDetails, setMovieDetails] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (typeof window !== "undefined") {
      try {
        initializeApp(firebaseConfig);
        console.log("Firebase initialized successfully");
      } catch (error) {
        if (!/already exists/.test(error.message)) {
          console.error("Firebase initialization error", error.stack);
        }
      }

      const fetchMovieDetails = async () => {
        setIsLoading(true);
        setError(null);

        const { id } = router.query || {};
        console.log("router.query:", router.query);

        console.log("Movie ID:", id);
        const db = getFirestore();

        try {
          const docSnap = await doc(collection(db, "movies"), id).get();
          console.log("docSnap:", docSnap);

          if (docSnap.exists) {
            setMovieDetails(docSnap.data());
          } else {
            setError("Movie not found");
          }
        } catch (error) {
          console.error("Error fetching movie details:", error);
          setError("Failed to fetch movie details: " + error.message);
        } finally {
          setIsLoading(false);
        }
      };

      fetchMovieDetails();
    }
  }, [router.query]);

  return (
    <div>
      {isLoading ? (
        <p>Loading movie details...</p>
      ) : error ? (
        <p>{error}</p>
      ) : movieDetails ? (
        <>
          <h1>{movieDetails.title}</h1>
        </>
      ) : (
        <p>No movie details available</p>
      )}
    </div>
  );
};

export default MovieDetail;

Here is the firebase.js file

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import firebaseConfig from "./firebaseConfig";

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

export default db;

By the way, the code for the grid displaying "movies" is functioning properly and retrieving the IDs without any issues

"use client";

import React, { useState, useEffect } from "react";
import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from "firebase/firestore";
import Image from "next/image";
import Link from "next/link";
import firebaseConfig from "../firebaseConfig";
import Search from "@/components/Search/Search";
import "./s.css";

const Page = () => {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    if (typeof window !== "undefined") {
      try {
        initializeApp(firebaseConfig);
        console.log("Firebase initialized successfully");
      } catch (error) {
        if (!/already exists/.test(error.message)) {
          console.error("Firebase initialization error", error.stack);
        }
      }

      const fetchData = async () => {
        try {
          console.log("Fetching data...");
          const db = getFirestore();
          const moviesCollection = await getDocs(collection(db, "movies"));

          const moviesData = moviesCollection.docs.map((doc) => ({
            id: doc.id,
            ...doc.data(),
          }));

          setMovies(moviesData);
          console.log("Data fetched successfully:", moviesData);
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      };

      fetchData();
    }
  }, []);

  return (
    <div>
      <Search />
      <main>
        <div className="hero-container">
          {movies.map((movie) => (
            <div key={movie.id} className="main-container">
              <div className="poster-container">
                <Link href={`/movie/${movie.id}`} passHref>
                  <Image
                    src={movie.posterUrl}
                    className="poster"
                    width={230}
                    height={350}
                    alt={movie.title}
                  />
                  <p>
                    {movie.title} ({movie.year})
                  </p>
                </Link>
              </div>
            </div>
          ))}
        </div>
      </main>
    </div>
  );
};

export default Page;

Answer №1

Within your code, the single instance of calling doc() is shown below:

const docSnap = await doc(collection(db, "movies"), id).get();

If an error arises from this line, it appears that the variable id may not be assigned a value.

To confirm this issue, you can either debug the code or add a console.log(id) before its usage:

console.log(id);
const docSnap = await doc(collection(db, "movies"), id).get();

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 there a way to retrieve the objects generated by DirectionsRenderer on Google Maps V3?

Is there a simple method to access the objects and properties of the markers and infowindows that are generated by the DirectionsRenderer? (such as the "A" and "B" endpoints of the route) I want to swap out the infowindows for the "A" & "B" markers wi ...

No matter the way I input the URL in the AJAX call, the response always comes back as successful

I ran into an issue with my ajax request. It was supposed to be a GET request that returned some data, but no matter how I configured the URL, it always gave a success response even when it didn't actually succeed. var id = 5; $.ajax({ type: ...

Javascript favorite star toggling

An excellent illustration is the star icon located on the left side of this post. You have the ability to click on it to save this message as a favorite and click again to remove the flag. I have already set up a page /favorites/add/{post_id}/, but I am ...

Exploring the concept of inheritance in JavaScript and Angular programming

Currently, I am working on a project called "hello world" and it involves two HTML pages named "configuration.html" and "add configuration.html". Each page has its own controller defined as follows: angular.module('MissionControlApp').controller ...

What is the most efficient method for creating and adding an element in jQuery?

When it comes to appending div elements to a page, there are different approaches that can be taken. Let's explore two methods: $('#page123').append("<div id='foo' class='checkbox' data-quesid='foofaa'>&l ...

What is the best way to create an HTML5 Range that gracefully degrades?

I want to incorporate the <input type='range' /> element from HTML5 for modern browsers and fallback to a <select /> if needed. Since I am working with Ruby-on-Rails, as a last resort, I could implement something similar to this on th ...

Determine whether it is SSR or not

I have developed a versatile package designed for compatibility with both CRA and NextJS environments. Within this package, there is a crucial component that configures attributes on body, html, and title tags. To achieve this functionality, I initially ...

Store data in LocalStorage according to the selected value in the dropdown menu

Can you help me understand how to update the value of a localstorage item based on the selection made in a dropdown menu? <select id="theme" onchange=""> <option value="simple">Simple</option> <option valu ...

Create a path on the Google Map that follows the designated route

I am looking for a solution similar to one found here: Sample However, I have been unable to find a suitable solution anywhere. The main issue is being able to follow the route in order to draw a line between two points. Can anyone provide guidance on ho ...

What is the best way to wrap the countdown numbers with <span> tags?

I have implemented the following countdown script: var clock = document.getElementById("timeleft"), tdy = new Date(1494979200000); countdown.setLabels( '| <span class="time-label">second</span>| <span class="time-label">minute< ...

The tabs in bootstrap appear to be functioning properly, but the data is not displaying as expected

Currently, I am incorporating Bootstrap into my project and I am attempting to include a Twitter Bootstrap tab. I have already added jQuery and bootstrap-tabs.js to my project. Below is the script that I have added: <script> $('#myTab a&apos ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

Changing text content of an element with dynamic formatting

When a link is clicked on, I want to dynamically set the text. Here is the current code: <a href="www.somelinkhere.com" onclick="getElementById('setText').innerHTML='text to replace'" target="someIFrame" ...

How do I fetch the most recent post from MongoDB using Next.JS?

I'm currently working on a comment app, but I've encountered an issue where the latest post/comment appears at the bottom. I'd like to have new comments display at the top instead. Can anyone guide me on how to achieve this? Thank you. impor ...

Establish routes in Angular depending on a certain condition

Within my app.js file, I am setting up routes to direct to various controllers using the following code snippet: var urlArray=['Suggest','Comment']; var pdfURL="Suggest"; app.config(function($routeProvider,$locationProvider) { .w ...

Guide to selecting a date using JavaScript in Selenium with Ruby

I'm having some trouble selecting a date from a date picker field using JavaScript in Selenium WebDriver. I've attempted the code below, which does navigate to the date window successfully, but I can't figure out how to execute the JavaScrip ...

What is the best way to delay the loading of a JavaScript script on my website for 20 or 30 seconds

Is there a way to load the following JavaScript ad after 30 seconds on my WordPress site? <script type="text/javascript"> var uid = '219412'; var wid = '586053'; var pop_tag = document.createElement('script ...

Geometry is making its debut appearance in ThreeJS for the very first time!

Currently, I am experimenting with a simple script using ThreeJS to create a point wherever you click on the screen. Below is the function responsible for adding the point: function addPoint(coord){ var geometry = new THREE.BufferGeometry(); var verti ...

Encountering a peculiar issue with including no-cors in the header while fetching JSON content in a React.js application

As someone who is relatively new to react and nodeJS, I am currently experimenting with pulling JSON data from my nodeJS webservices and displaying it in a react component. let url = "http://codepen.io/jobs.json"; let iterator = fetch(url); iterator ...

Is there a way to transfer an array I obtained from a different file into a new array?

When I retrieve an array from another file, I am only able to display the entire array. I am unable to display a specific element or assign it to another array. Below is a snippet of the code: Here is my .js file that runs on node and sends the arrays: v ...