1

Nuxt.js is focuses on server side rendering and has an asyncData property that is called once before the page component is loaded.

I am trying something like:

async asyncData({params}) {
    // firebase.auth().onAuthStateChanged((user)=>{ // <-- this doesn't work in the asyncData property
      let user = await firebase.auth().currentUser
      let info = {}
      console.log(user)

      user.uid === null // true
}

Two similar questions:

have solutions which do not seem to work with nuxt...

I have also tried:

function getCurrentUser(auth) {

  let userLoaded = false;
  return new Promise((resolve, reject) => {
     if (userLoaded) {
          resolve(firebase.auth().currentUser);
     }
     const unsubscribe = auth.onAuthStateChanged(user => {
        userLoaded = true;
        unsubscribe();
        resolve(user);
     }, reject);
  });
}

KENdi
  • 7,576
  • 2
  • 16
  • 31
SumNeuron
  • 4,850
  • 5
  • 39
  • 107
  • I think the problem comes from the fact that `onAuthStateChanged` does not return a promise but **adds an observer** for changes to the user's sign-in state, see https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged – Renaud Tarnec Mar 14 '19 at 10:03
  • @RenaudTarnec yeah, which is why I also tried without it... I have also wrapped `currentUser` in a promise and it doesnt work – SumNeuron Mar 14 '19 at 10:04
  • I'm trying to achieve the same thing. Any updates? – Jonas Apr 25 '19 at 20:25
  • I believe it doesn't work that way. asyncData() is run in server side when loading for the first time. There won't be any currentUser instance in server side. It's only available in the client side. – Yaobin Then May 31 '19 at 01:41

1 Answers1

0

It seems like onAuthStateChanged is triggered on client-side only. But the thing is, SSR functionality would make sense only for non-authenticated users, for authed-user scenario might as well just put the firebase call logic into mounted hook.

Be Kind
  • 4,712
  • 1
  • 38
  • 45