Import error firebase/firestore using react

I have a problem with firestore. I want to read some data from firebase but I can’t import collection from firebase Attempted import error: ‘collection’ is not exported from ‘firebase/firestore/’. I read some articles that said this problem is related to v9 SDK.




You have to import the Firebase SDKs correctly. The issue is in the first line where you are importing from “firebase” directly which is not the ideal method and as per my understanding, the import calls/methods are not in sync with the version changes. Be sure to read the documentation on using Firebase with module bundlers

Starting with Firebase v8.0.0, you have to import Firebase SDKs as per the documentation where it is mentioned that there was a breaking change in version 8.0 where

browser fields in package.json files now point to ESM bundles instead of CJS bundles. Users who are using ESM imports must now use the default import instead of a namespace import

Before 8.0.0

import * as firebase from 'firebase/app'

After 8.0.0

import firebase from 'firebase/app'

Code that uses require('firebase/app') or require('firebase') will still work, but you should change these require calls to require('firebase/app').default or require('firebase').default

Change your code as shown below :

import firebase from "firebase/app" 
import { getFirestore } from "firebase/firestore";
import { collection, addDoc, getDocs } from "firebase/firestore";
import "firebase/auth" 
const auth = firebase.auth()

This should work for you. If not, then probably you have updated your SDK version from 8 to 9 and with version 9 things changed a bit for importing firebase, but there is no need to downgrade to a previous version, there is a “compatibility” option so can use the /compat folder in your imports, like this

import firebase from 'firebase/compat/app';

From the Firebase documentation:

In order to keep your code functioning after updating your dependency from v8 to v9 beta, change your import statements to use the “compat” version of each import as shown below (v9 compat packages are API compatible with v8 code) :

import firebase from 'firebase/compat/app'; 
import 'firebase/compat/auth'; 
import 'firebase/compat/firestore';