Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use firebase auth and Cloud Firestore from different components as a single firebase App

I am trying to use firebase in my React project to provide the auth and database functionalities.

In my App.js I have

import app from "firebase/app";
import "firebase/auth";
app.initializeApp(firebaseConfig);

In my other components called <Component /> rendered by App.js I have this to initialize the database

import app from "firebase/app";
import "firebase/firestore";
const db = app.firestore();

However this time I got this error

Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

So I tried to put app.initializeApp(firebaseConfig); in this component too but I got a new error again to tell me I instantiated twice.

Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).

So one workaround I came up with is to create a context at App.js and right after app.initializeApp(firebaseConfig); I created the database by const db = app.firestore(); and pass the value to the context and let the <Component /> to consume. However I don't know if this is a good solution or not.

My question is different from How to check if a Firebase App is already initialized on Android for one reason. I am not trying to connect to a second Firebase App as it was for that question. There is only one Firebase App for my entire project, to provide two services: auth and database.

I tried the solution from that question to use in <Component />

if (!app.apps.length) {
  app.initializeApp(firebaseConfig);
}

const db = app.firestore();

but it didn't work it still gives me Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). error

like image 857
Joji Avatar asked Jul 27 '19 18:07

Joji


1 Answers

You use different instances of Firebase in App and Component.

// firebaseApp.js
import firebase from 'firebase'
const config = {
    apiKey: "...",
    authDomain: "...",
    databaseURL: "....",
    projectId: "...",
    messagingSenderId: "..."
};
firebase.initializeApp(config);
export default firebase;

Than you can import firebase from firebaseApp.js and use it. More details here

like image 142
Valerii Avatar answered Oct 04 '22 02:10

Valerii