简体   繁体   中英

JS, firebase.auth() doesn't work in global context but works inside the functions? - firebase.Auth is not a function

I have imported all the firebase scripts I need at the bottom of my HTML

<body>
 ...
  <script src="/__/firebase/8.0.1/firebase-app.js"></script>

  <script defer src="/__/firebase/8.0.1/firebase-auth.js"></script>
  <script defer src="/__/firebase/8.0.1/firebase-firestore.js"></script>
  <script defer src="/__/firebase/8.0.1/firebase-functions.js"></script>

  <script defer src="/__/firebase/init.js?useEmulator=true"></script>

  <script src="./scripts/app.js"></script>
</body>

and inside my app.js I'm useing firebase.auth() on form submit and it works fine.

loginForm.addEventListener('submit', (e) => {
  e.preventDefault();
  const email = loginForm.email.value;
  const password = loginForm.password.value;

  firebase
    .auth()  -> works fine here!
    .signInWithEmailAndPassword(email, password)
    .then((user) => {
      console.log('signed in', user);
      loginForm.reset();
    })
    .catch((error) => {
      loginForm.querySelector('.error').textContent = error.message;
    });
});

But the problem occurs when i try to write onAuthStateChanged in global context of app.js

  firebase.auth().onAuthStateChanged((user) => {
    ....
  });

 // throws an error "Uncaught TypeError: firebase.Auth is not a function"

funny thing is that when I console.log(firebase) it logs out correctly and I can see auth as well other methods like functions. By the way this applies to other firebase methods and not only auth .

Is this some kind of bug ?

This happened to me as well. This is not specific to firebase and turns out you cannot call any function directly in a global context. I suggest you place it in the componentDidMount function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM