4

In a React application, I usually initialize firebase like this:

if (firebase.apps.length < 1) {
  firebase.initializeApp(firebaseConfig);
  // Initialize other firebase products here
}

This worked perfectly until I upgraded to v9 beta. How do I make it work for the new version?

1
  • On a note, you are no longer required to check if there's a default instance of Firebase already in the new SDK.
    – Dharmaraj
    Nov 4, 2021 at 14:32

2 Answers 2

16

The correct way to do it is to use getApps():

import { getApps, initializeApp } from "firebase/app";

if (getApps().length < 1) {
  initializeApp(firebaseConfig);
  // Initialize other firebase products here
}
-1

A simple solution that has worked for me for v9 is this:

import { initializeApp } from "firebase/app";

let firebase;

if (!firebase) {
  firebase = initializeApp(config)
}
4
  • 2
    You are checking if firebase is false, undefined, or null. If it is any of those, why would the initializeApp function be defined?
    – Shivam
    Nov 4, 2021 at 13:11
  • Right, good catch. I jumbled v8 and 9 here. I edited my answer.
    – Max
    Nov 4, 2021 at 14:28
  • Yes. Also, you can just import the method you want to use without using the firebase constant at all.
    – Shivam
    Nov 4, 2021 at 19:17
  • I'm just exporting it for use in other files where I need it for getFunctions(), getAuth(), etc.
    – Max
    Nov 4, 2021 at 21:56

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.