Firebase Error: The first argument provided to the collection() method should be either a CollectionReference, a DocumentReference, or FirebaseFirestore

My task involves creating a variable to reference a Firestore document.

const userRef = doc(db, 'users', uid)

I want to use it by adding a Realtime listener.

onSnapshot(userRef,  (doc) => {
        if (doc.exists()){
            setCode(code = doc.data().keycode)
        } else {
            setCode(code = 'N/A')
        }
    })

However, I encountered this error:

FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

Initially, I thought the issue was with the uid being incorrect, so I tried hard coding it but still faced the same error.

Below is the complete code for a react component where I imported the firebase config from App.js

import React, { useState } from 'react'

import { onSnapshot, doc, getFirestore } from 'firebase/firestore'

function Transaction(uid, firebase) {
    const db = getFirestore(firebase);

    let [amount, setAmount] = useState('')
    let [target, setTarget] = useState('')
    let [code, setCode] = useState('')

    const userRef = doc(db, 'users', uid)
    
    const sendNum = async(e) => {
        e.preventDefault();
        console.log('Send Num')
    }

    const generateCode = async(e) => {
        e.preventDefault();
        console.log('Generate Code')
    }


    onSnapshot(userRef,  (doc) => {
        if (doc.exists()){
            setCode(code = doc.data().keycode)
        } else {
            setCode(code = 'N/A')
        }
    })

    return (
        <>
            <form onSubmit={sendNum}>
                <input style={{ width: 200 }}value={amount} onChange={(e) => setAmount(e.target.value)} type="number" placeholder='Amount'/>
                <input style={{ width: 200 }} value={target} onChange={(e) => setTarget(e.target.value)} type="number" placeholder='Keycode'/>
                <br />
                <button className='btn' type='submit'>Send</button>
            </form>
 
            <section>
                <h2>{code}</h2>
                <button className='btn' onClick={generateCode} type='submit'>Generate Code</button>
            </section>
        </>
    )
}

export default Transaction

In using React Router, I passed the props accordingly:

const firebaseConfig = {
  apiKey: "AIzaSyAKLyeY2FbjFDD57Kp9sGDi8uHg3neXxjI",
  authDomain: "digitots-dev.firebaseapp.com",
  projectId: "digitots-dev",
  storageBucket: "digitots-dev.appspot.com",
  messagingSenderId: "150130182744",
  appId: "1:150130182744:web:216e77264273772c94182d",
  measurementId: "G-RJT8Q1LSXZ"
};

const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getFirestore();
const provider = new GoogleAuthProvider();

let uid = ''

function App() {
  
  
  return (
    <div className="App">
      
      <header>
        <Router>
          <Nav />
          
          <Switch>
            
            <Route path='/' exact component={MainView} />
            <Route path="/about" component={About}/>
            <Route path='/shop' component={Shop}/>
            <Route path='/admin' component={Admin}/>
            
            <Route
              path='/portal'
              render={(props) => (
                <Transaction {...props}  db={db} uid={uid} firebase={firebaseConfig}/>
              )}
            />
            

          </Switch>
           
        </Router>
      </header>

      
    </div>
  );
}

https://i.sstatic.net/YkHTi.png

Answer №1

It seems like the error message is indicating that when using doc(), there is an issue with the first argument being passed to it, resulting in the error

Expected first argument to collection()
. This often happens when the variable db is either undefined or not correctly initialized as an instance of Firestore. To resolve this, ensure that you import db from the appropriate file where Firestore is initialized, or make sure it is defined within the same file:

import { getFirestore, doc } from "firebase/firestore"

const db = getFirestore(app) // const app = initializeApp(fireConfig)

const userRef = doc(db, 'users', uid)

Regarding the error

TypeError: Cannot read property 'getProvider' of undefined
:

<Transaction {...props}  db={db} uid={uid} firebase={firebaseConfig}/>

The issue here lies in passing the Firebase configuration (a JSON object) into getFirestore() instead of the expected Firebase app instance.

// Incorrect
const db = getFirestore(firebase);


// Correct
const db = getFirestore(firebaseApp)

To fix this, update the Transaction component as follows:

<Transaction {...props} uid={uid} firebase={firebaseApp}/>

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

"Node.js mystery: Why does a function call return undefined, only to be evaluated

Utilizing the async module, I am running a series of functions in parallel. However, I have encountered an issue where the return value of another function is undefined because the callback does not wait for it to be evaluated. function getGenresId(genres ...

Ways to Retrieve Material-UI Date Picker Data

I am struggling to figure out how to set the value selected by the user in a material-ui datepicker to state. Any help would be greatly appreciated. Currently, this is what I have been trying: The datepicker component code looks like this: <DatePicke ...

shimmering jquery effects

Hello everyone! I'm currently working on building my website at (just a heads up, it's still in the early stages so please be kind haha). Take a look at the menu - it seems to be causing a flickering issue in Chrome and Safari but works fine in ...

What are some alternatives to using iframes?

Currently, I am working on a project for a client where I need to display multiple websites on a single page in a browser. To achieve this, I initially used the iframe element, but encountered an issue with the openerp frame. Despite setting up the openerp ...

Transform your Django CoffeeScript conversion tool with a jQuery call(this) function

I am currently working on a project with django-coffeescript. However, I am encountering some issues with the conversion process. Within my hello.coffee file: hello = ()-> console.log 'Hello' After conversion, it looks like this: // Gene ...

Issue with the gulp-babel plugin: Files within the Plugin/Preset should only export functions, not objects

I have started to integrate JavaScript 2015 (ES6) into my Ionic v1 app: package.json { "name": "test", "version": "1.0.0", "dependencies": { "@ionic-native/deeplinks": "^4.18.0", "cordova-android": "7.0.0", "cordova-android-support-gra ...

Avoiding the need to wait for completion of the jQuery $.get function

Currently, I am executing a basic jQuery GET request as shown below and it is functioning correctly. $.get("http://test.example.com/do-something", function (data) { console.log("test work done"); }); The GET request is initiated without affecting the ...

Deploying CSS/JS files in Magento 2 is a crucial

Hello, I recently set up magento2 with the sample data included. After attempting to deploy static css/JS using the command php bin/magento setup:static-content:deploy, I didn't receive any errors but the issue persists. Additionally, I am unable to l ...

Is there a way to extract a username from LDAP?

Can you help me understand how to dynamically retrieve a username from LDAP? In the code snippet below, I have hardcoded the username as 'smith2': $_SERVER["REMOTE_USER"] = 'smith2'; $param = $_SERVER["REMOTE_USER"] By using this appr ...

Sending the complete data from an HTML table to a web method

Is there a way to pass the data from a dynamically generated HTML table grid to a web method using jQuery AJAX? The table grid creates multiple rows on button click at runtime, and I need to send the entire table data. Please refer to the following snaps ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...

When using Owl Carousel in Chrome, the carousel unexpectedly stops after switching tabs

Hi there, I'm currently testing out the auto play feature in owl carousel. One issue I've encountered is that when I switch to another tab in Chrome and then return to my webpage with the carousel, it stops functioning unless I manually drag the ...

Unable to load JSON information into an ExtJS grid

I have exhausted all the solutions I found (there are many on Stackoverflow) in an attempt to fix my extjs store issue. Despite ensuring that the grid is displayed correctly, the data still refuses to show up. Feeling perplexed, I am sharing the "store" co ...

The functionality of drag and drop in Chrome 91 seems to be unresponsive when utilizing Selenium WebDriver, Action Class, and JavaScript

Recently, I have encountered an issue with the drag and drop functionality in Chrome version 91 while using Selenium Action class or Java script. Despite trying various approaches, including: Using a custom JavaScript method for drag and drop. JavaScript ...

New to Django - Seeking assistance with concealing sections of a dynamically generated table

I am working on a dynamic table where I need to show or hide certain parts based on the state of corresponding checkboxes. When a checkbox is unchecked, I want to hide the specific section of the table with the class "newtable" for that row only. Each row ...

What is the best approach to gather both the intersection and the complements of two arrays in a single operation?

Comparing Arrays - const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; Initializing Arrays - const matches1 = []; const matches2 = []; const unmatches1 = []; Array Matching Process - for (const line of source) { const line2Match = target.fi ...

I came across a fascinating finding during my JavaScript studies, but its origin remains a mystery to

I recently wrote some code and was surprised to find that it did not generate any output. Here is the snippet of code: var a1 = undefined; var a2 = 5; if(a1 > a2) alert(1); if(a1 < a2) alert(2); if(a1 >= a2) alert(3); if(a1 <= a2) ...

Use the knockout textInput plugin in combination with the maskedinput plugin

Is there a simple way to use data-bind="textInput: aProperty" and apply an input mask or automatic formatting while the user is typing? Although using the masked input plugin somewhat works, it results in losing the real-time updates that Knockout's ...

What is the most effective way to link JavaScript events in a substantial web development venture?

Typically, I use a single .js file for my projects, occasionally splitting it into separate files for front and back end sections. Within these files, event handlers are attached using jQuery selectors inside a single jQuery ready event handler like so: $ ...

Using the AJAX loading method with an ID stored in a JavaScript variable

Hey there! Could someone please explain how I can use the AJAX load method to load a div whose ID is stored in a JavaScript variable? In other words, the div that needs to be loaded has its ID saved as a JavaScript variable. I'm facing an issue where ...