Wednesday, 31 July 2019

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



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

No comments:

Post a Comment