Home > Enterprise >  Nested Javascript async/await not being fired - Nuxt & Firebase Auth
Nested Javascript async/await not being fired - Nuxt & Firebase Auth

Time:11-11

I'm writing a basic middleware for NuxtJS 3 for authentication using Firebase and just need some help with proper chaining and nesting syntax. Here's my code:

import { onAuthStateChanged } from 'firebase/auth';
import { getDoc, doc } from 'firebase/firestore';
import { auth, db } from '~/plugins/firebase';

export default async function ({ redirect }) {
  await onAuthStateChanged(auth, (user) => {
    if (user) {
      const documentRef = doc(db, 'users', user.uid);

      const getDocData = async () => {
        const docSnap = await getDoc(documentRef);

        if (docSnap.exists()) {
          console.log('Document data:', doc.data());
        }
      };
    }
  });
}

Most of it works, but the const getDocData... isn't firing and of course it's because I'm not even calling it but I have tried for hours to come up with a clean solution and nothing seems to be working so far.

CodePudding user response:

You need to declare the callback async, as follows:

onAuthStateChanged(auth, async (user) => {
  if (user) {
    const documentRef = doc(db, 'users', user.uid);
    const docSnap = await getDoc(documentRef);

    if (docSnap.exists()) {
      console.log('Document data:', docSnap.data());
    }
  }
});

Also note that you need to change doc.data() to docSnap.data().

  • Related