Home > Back-end >  Firebase Reactjs - ae.collection is not a function
Firebase Reactjs - ae.collection is not a function

Time:10-14

I can't figure out what is the error here. I made the tutorial Firebase/website and did the same things in my project. I am trying to print out the collection I created on Firebase in my React website but got the error at the line db.collection : Uncaught (in promise) TypeError: ae.collection is not a function

component.js :

// React
import { useState, useEffect } from "react";
import { db, collection, getDocs  } from '../../../firebase.js';

const [holder, setHolder] = useState([]); // update
  
  db.collection("holder").onSnapshot((snapshot) => {
    setHolder(
      snapshot.docs.map((doc) => ({
        id: doc.id,
        data: doc.data(),
      }))
    );
  });
  console.log({ holder });

update : firebase.js below

    // Import the functions you need from the SDKs you need
    import { initializeApp } from "firebase/app";
    import { getAnalytics } from "firebase/analytics";
    import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries
    
    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
...
    };
    
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
    
    export const db = getFirestore(app);

Thank you !

CodePudding user response:

You are using Firebase Modular SDK which has a completely new syntax and you must use the same in your code. Try refactoring the code to this:

// React
import { useState, useEffect } from "react";
import { db } from '../../../firebase.js';
import { onSnapshot, collection } from 'firebase/firestore'

const [holder, setHolder] = useState([]); // update
 
onSnapshot(collection(db, 'holder'), (snapshot) => {
  setHolder(
    snapshot.docs.map((doc) => ({
      id: doc.id,
      data: doc.data(),
    }))
  );
})

Also make sure your getFirestore import is from firebase/firestore and not from lite in firebase.js or you'll run into this issue:

import { getFirestore } from 'firebase/firestore';
  • Related