Error in Firebase: The first argument provided to collection() must be a valid CollectionReference, DocumentReference, or FirebaseFirestore

Wow, this one has been quite a challenge for me. I had to go back to firebase9.4.0 in order to pinpoint where my code was causing errors.

The error: https://i.sstatic.net/DLNPZ.png

In a separate file named queries.config.js, I gather all the necessary subcollections:

import { query, collection, getDocs } from "firebase/firestore";
import { db } from "../firebase/firebaseConfig";

const q1 = query(
    collection(db, "hairstyles/locs-hair-treatment/Locs Hair Treatment")
);
const q2 = query(
    collection(
        db,
        "hairstyles/locs-styles & protective-styles/Locs Styles & Protective Styles"
    )
);
// Remaining queries omitted for brevity

export { q1, q2, ... };

Here's a snippet of my firebaseConfig file:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    // Remaining config details omitted for brevity
};

console.log(firebaseConfig);

// Initializing Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getFirestore();

export { auth, db };

Answer №1

To resolve the issue at hand, it is essential to note that in firebase 9.x, the initialization methods such as getFirestore, getAuth, and getStorage require a firebase app as a parameter.

Your code seems to be lacking the necessary implementation, which includes:

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

I strongly believe that the solution lies in passing the app as a parameter to the getFirestore method. In order to demonstrate this, I have created a basic Next JS application where data is fetched from a collection using a query.

The version of firebase being used is

"firebase": "^9.17.2"

Firebase configuration file:

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

const firebaseConfig = {
  apiKey: "some_api_key",
  authDomain: "some_auth_domain",
  projectId: "some_project_id",
  storageBucket: "some_storage_bucket",
  messagingSenderId: "some_messaging_sender",
  appId: "some_app_id"
};

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

export default DB

index.jsx file:

import React, { useState } from "react";
import DB from "../core/firebase";
import { collection, query, getDocs, where } from "firebase/firestore";

function Header({ title }) {
  return <h1>{title ? title : "Default title"}</h1>;
} // This component is a starter component from NextJS

export default function HomePage() {
  const [cases, setCases] = useState([]);
  const [loading, setLoading] = useState(false)

  const renderList = cases.map((item, idx) => <div key={idx}>{item.topic}</div>);

  async function handleClick() {
    setLoading(true) 

    const q = query(
      collection(DB, "Cases"),
      where("email", "==", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e34313630013a313b1e39333f373c313832">[email protected]</a>")
    ); 

    const querySnapshot = await getDocs(q); 
    
    const records = []; 
    querySnapshot.forEach((doc) => {
      records.push(doc.data());
    });

    setCases(records); 

    setLoading(false) 
  }

  return (
    <ul>
      <Header title="Fetching firestore data 🚀" />
      <button style={{marginBottom: 10}} onClick={handleClick}>Fetch</button>
      {loading && <div>Loading...</div>}
      {cases && renderList}
    </ul>
  );
}

You can find the complete code on Github by visiting: Github repository

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

One-of-a-kind browser identification for users, no login required

I have an online boutique and I want to enable customers to make purchases without creating an account. To achieve this, I need a way to associate a selected list of items with a user. Initially, I considered using the IP address for this purpose but fou ...

Changing text color based on positive or negative value in JavaScript(React)

Greetings everyone! I'm currently working on a specific feature that requires the color of a value to change dynamically. If the value is above 0, it should be displayed in green; if below 0, in red; and if equal to 0, in orange or yellow. To achieve ...

Angular: Enhance communication with controllers and directives

Currently, I am in the process of learning Angular. One interesting feature I have been working on is a directive that displays a select element. Whenever there is a change in this select element due to the ng-change event, a specific method defined in the ...

Utilize Angular to transform a standard text string within a JSON object into a properly formatted URL

Welcome to my first Stack Overflow question! I usually find the answers I need on my own, but this time I could use some guidance as I delve into Angular. I have a directive that pulls the name and URL from a JSON object and generates HTML with the name a ...

Converting RGB color values to HSL color values using a unique, randomized Javascript approach

On this site, I have added a random color overlay to the media-boxes. Check it out here Thanks to the helpful folks at stackoverflow, I was able to create this script: var getRandomInRange = function(min, max) { return Math.floor(Math.random() * (ma ...

I am facing an issue where the module pattern functions perfectly on JSBin, but fails to work properly

As a backend developer, I typically only write JavaScript when absolutely necessary, and not always in the best way. However, I have decided to turn over a new leaf and start writing more organized code that follows best practices as much as possible. To ...

"Facing an issue with Google Chrome not refreshing the latest options in an HTML select dropdown list

Having trouble creating an offline HTML file that incorporates jQuery for the script. The page features a state select menu followed by a second menu for counties. When a state is selected, only the corresponding counties should display while others remai ...

What are different ways to modify a bytearray within a file using angular js, whether it is an .xlsx or other

I received a bytearray response from my API that was converted from a .xlsx file. I now need to open or download this bytearray in the browser after converting it back to its original file extension. Can anyone provide guidance on how to achieve this? I ...

The React Component is not displaying any content on the webpage

I developed a Reactjs application using the create-react-app. However, I am facing an issue where the components are not displaying on the page. I suspect that App.js is failing to render the components properly. Take a look at my code: App.js import R ...

Roundabout Navigation Styles with CSS and jQuery

My goal is to implement a corner circle menu, similar to the one shown in the image below: https://i.stack.imgur.com/zma5U.png This is what I have accomplished so far: $(".menu").click(function(){ $(".menu-items").fadeToggle(); }); html,body{ colo ...

Is there a way to identify the index of user input when using the .map method?

I'm currently utilizing the Array.prototype.map() method to present an array within a table. Each row in this table includes both an input field and a submit button that corresponds to each element from the Array.prototype.map() function. Is there a w ...

Make sure to always select the alternative option in ajax

I am trying to create a condition where if the value of id=type_investor is either 1 or 6, an email should be sent using a different controller. Here is my complete code: function (isConfirm) { if (!isConfirm) return; $.ajax({ ...

By using Yii2, you can pass an id to the URL by simply clicking on a

I am struggling with sending the post_id from a div containing text content (retrieved from a database) to a URL in order to render a view page displaying the entire content. I am using Yii2 and believe I need to use JavaScript for this task, but I am unsu ...

Storing User IP Address in Database with Express and Mongoose

I'm looking for a way to store users' IP addresses in mongoDB by using a mongoose model file for the user. Does anyone have any suggestions on how I can achieve this? Here is an example of the schema for the Users module file: const userSchema ...

Creating functional dropdown menus with popperjs in the latest Bootstrap version 5

Currently, I am attempting to implement dropdown menus in Bootstrap 5. According to my research, this feature requires Popper.js integration, but I am uncertain of the correct way to include it in my Laravel project that utilizes Laravel Mix. I have made ...

Utilizing JavaScript Fetch with User Input to Integrate OpenWeather API Retains Previous Data on HTML Page

I have been working with JavaScript Fetch to retrieve data from the OpenWeather API. In my project, I have created a form where users can input the name of a city to view its weather information. However, I am facing an issue where the data from the previo ...

Changing the State of a CheckBox with ReactJS and Material UI

Utilizing Material UI's Checkbox, I am creating a form to input data and update or add values into a state object. This form serves the purpose of both editing an existing holiday or adding a new one. I'm currently facing an issue where the stat ...

Discovering the value of an item when the editItem function is triggered in jsGrid

Within my jsGrid setup, I have invoked the editItem function in this manner: editItem: function(item) { var $row = this.rowByItem(item); if ($row.length) { console.log('$row: '+JSON ...

The performance of the Ionic app is significantly hindered by lagging issues both on Google

After starting to work with the ionic framework, I noticed a significant change in performance when testing an android app on Chrome for the first time. It was fast and responsive until I added a button that led to a screen with navigation bars, side men ...

Identifying Changes with jQuery Event Listeners

I am trying to run some javascript code that is in the "onchange" attribute of an HTML element. For example: <input id="el" type="text" onchange="alert('test');" value="" /> Instead of using the onchange attribute, I want to trigger the e ...