Home > Enterprise >  TypeError: firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.firestore is not a function
TypeError: firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.firestore is not a function

Time:09-21

Just trying to set it up firebase for the first time and I get these errors cant find any right answer to work this is my config

// Import the functions you need from the SDKs you need
import firebase from 'firebase/compat/app';
import 'firebase/firestore';
import {
  initializeApp
}
from "firebase/app";
// 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
const firebaseConfig = {
  apiKey: "x",
  authDomain: "x",
  projectId: "x",
  storageBucket: "x",
  messagingSenderId: "x",
  appId: "x"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = firebase.firestore();
export {
  db
};

the error I get - TypeError: firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.firestore is not a function

it shows to the line const db = firebase.firestore();

CodePudding user response:

If you want to use the compat version of firestore you need to initialize the firebaseApp also with the compat version. I would recommend using the new SDK version for both:


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

const firebaseConfig = {
  apiKey: "x",
  authDomain: "x",
  projectId: "x",
  storageBucket: "x",
  messagingSenderId: "x",
  appId: "x",
};


const app = initializeApp(firebaseConfig);
const db = getFirestore();
export { db };

With the new SDK, you actually don't need such a file like before where you initialize your app and create the database instances. After you initialize your app with the new SDK you can just call getFirestore() without the need to have the firebaseApp for it. getFirestore() will automatically use the default app.

A realtime listener by using collection would look like this:

import { collection, onSnapshot } from "firebase/firestore";

const unsubscribe = onSnapshot(collection(db, "cities"), () => {
  // Respond to data
  // ...
});

// Later ...

// Stop listening to changes
unsubscribe();

When you read the Firebase enter image description here

  • Related