0

so, i'm trying to get a single document from a collection, using the id from the current user, the request [getDoc] works, but when i'm trying to return the information from the exported function is where i', having all the problems, the function is called but it acts before the function returns the values it needs, so it only gets undefined information, i've tryed with .then(), async functions but it doesn't work at all

this is on the main javascript file called by the html <•script type="module" src="./Home.js">

window.addEventListener('DOMContentLoaded', async() => {
    UserStatus()
    
    const userinfo = await getUserInfo('UniversityStaff');
    //.then((userinfo) => {
        console.log(userinfo.data())
    //     const userProfile = userinfo.data();
    //     let html ='';
    //     html+=`
    //     <h5><b>Usuario:</b>${userProfile.userName}</h5>
    //     <h5><b>Correo institucional:</b>${userProfile.email}</h5>
    //     <h5><b>Telefono:</b>${userProfile.phone}</h5>
    //     <h5><b>Departamento:</b>${userProfile.area}</h5>
    //     <h5><b>Puesto:</b>${userProfile.jobTitle}</h5>
    //     <h5><b>Horario:</b>${userProfile.workingHours}</h5>`
    
    //     userInfo.innerHTML = html;
    // })
    })

this is the javascript file that contains all the code from the firebase modules. this is imported by the ./Home.js

export const getUserInfo = (collection) => {
       onAuthStateChanged(auth, (user) => {
        if (user) {
          getDoc(doc(db, collection, user.uid))
          .then((doc)=>{
            console.log(doc.data())
            return doc;

          })
        }
      })
    }
•this is the error from the [.then()/await] getting done before the [export const getUserInfo]

Home.js:14 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data') at Home.js:14:30 (anonymous) @ Home.js:14



•this is the data from the request on [export const getUserInfo]


firebase.js:112 {area: '', id: 'jX3J5XjwDphlE1rQRxlxOHyDqMI2', email: 'userExaple@gmail.com', phone: '6181690397', userName: 'Edmundo Gurrola', …}

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

The top-level code in your getUserInfo function doesn't return any value, so the await you use when calling that function is meaningless - as is the return doc inside the getDoc callback.

Since you want to await the async operations, you'll need to return a promise get getUserInfo:

export const getUserInfo = (collection) => {
  return new Promise((resolve, reject) => {
    onAuthStateChanged(auth, (user) => {
      if (user) {
        getDoc(doc(db, collection, user.uid)).then((doc)=>{            
          resolve(doc)
        })
      }
    })
  })
}

So the Promise that this code returns only resolves once the document has been loaded, meaning your await gets the result it expects.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807