1
votes

Feature: I want to automatically sign in with the user's profile if he or she successfully signed-in the previous web session.

Problem: I'm getting "No Firebase App" error in my React project while trying to execute firebase.auth(). The main firebase object initialization is triggered at the end of my index.js file with firebase.initializeApp(firebaseConfig). From what I can gather the firebase instance isn't properly initialized while executing authentication portion of code. Nomrally I would expect to perform the auth on the callback from the init function but there's none. So my question is what would be the best place to do the aforementioned automatic authentication/signing-in during the webpage load? Currently the authentication is performed on componentDidMount which obviously doesn't do the trick...

  componentDidMount = () => {
    if (localStorage.getItem("auth") == "google")
      this.authenticate();
  };
  authenticate = () => {
    var provider = new firebase.auth.GoogleAuthProvider();

    firebase // <- exception
      .auth() 
      .signInWithPopup(provider)
      .then(function (result) {
        // @ts-ignore
        var token = result.credential.accessToken;
        user = result.user;
        localStorage.setItem("auth", "google");
1
Did you try to put the firebase.initializeApp(firebaseConfig) at the beginning of index.js , before the component instead of the end ? - kunquan
Yes I tried it already (before ReactDOM.render portion of code) with the following error: Unhandled Rejection (TransactionInactiveError): A request was placed against a transaction which is currently not active, or which is finished - Eric

1 Answers

0
votes

Add in the body of your index.html:

<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script>

  <!-- Add analytics if you need them -->
  <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-analytics.js"></script>

  <!--Add firebase dependencies you need (here i added auth and firestore) -->
  <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-firestore.js"></script>
  
   <script>
    // TODO: Replace the following with your app's Firebase project configuration
    // For Firebase JavaScript SDK v7.20.0 and later, `measurementId` is an optional field
    var firebaseConfig = {
      // ... You can find config in settings, scroll down and click on cdn
      // I use cdn since it allows both external and firebase hosting
    };

    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
  </script>

Then you are ready to go