Reputation: 853
At first I was getting the "Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app)." error. I saw online that wrapping firebase initialization with "if (!firebase.apps.length) {}" would fix the problem. Now I'm getting an error that says "app is not defined". How do I work around this?
import firebase from "firebase/app";
import "firebase/auth";
if (!firebase.apps.length) {
const app = firebase.initializeApp({
apiKey: "process.env.REACT_APP_FIREBASE_API_KEY",
authDomain: "process.env.REACT_APP_FIREBASE_AUTH_DOMAIN",
projectId: "process.env.REACT_APP_FIREBASE_PROJECT_ID",
storageBucket: "process.env.REACT_APP_FIREBASE_STORAGE_BUCKET",
messagingSenderId: "process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID",
appId: "process.env.REACT_APP_FIREBASE_APP_ID"
});
}
export const auth = app.auth();
export default app;
Upvotes: 0
Views: 825
Reputation: 24922
An example with Firebase 9 / Modula — all you need to do with the example below is call initializeAppIfNecessary()
.
import { initializeApp, getApp } from "firebase/app";
function initializeAppIfNecessary() {
try {
return getApp();
} catch (any) {
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
projectId: "...",
};
return initializeApp(firebaseConfig);
}
}
const app = initializeAppIfNecessary();
Upvotes: 0
Reputation: 1283
I solved the issue this way :
let firebaseApp ;
if (!firebase.apps.length) {
firebaseApp = firebase.initializeApp(firebaseConfig);
}
else {
firebaseApp = firebase.app(); // if already initialized, use that one
}
export const auth = app.auth();
export default app;
The problem here is you are defining const app = ...
but it gets defined only for the if
scope ( it's how it works in js ). That's why initialize a variable using let
and then assign values to it
Upvotes: 1