Home > Software engineering >  Unable to receive data returned by a function
Unable to receive data returned by a function

Time:09-17

I am working on a React project. I have two files contact.js and functions.js.

In contact.js file

import {getUserContacts} from './functions.js';

 useEffect(() => {
    let temp=getUserContacts();
    console.log(temp);
  }, [])

In functions.js file

export const getUserContacts = () => {
  const contactDetailsArr = [];

  db.collection("users").doc(userId).get()
    .then(docs => {

      const contactsObject = docs.data().contacts;

      for (let contact in contactsObject) {

        db.collection("users").doc(contact).get()
          .then(userDetail => {
            contactDetailsArr.push({
              userId: contact,
              lastMessage: contactsObject[contact].lastMsg,
              time: contactsObject[contact].lastMsgTime,
              email: userDetail.data().emailId,
              active: userDetail.data().active,
              img: userDetail.data().imageUrl
            })

          })
      }
      
      return contactDetailsArr;

    })
    .catch(err => {
      console.log(err);
    })

}

As one can see in the functions.js when I console contactDetails I am able to see the data. But in contact.js when I console the returned data I get undefined.

Please guide me on why I am seeing such behavior.

CodePudding user response:

You might have this result if there's a delay in your function logic

CodePudding user response:

I hope your

//function logic

done have any async stuff, otherwise

contactDetails

would be undefined at the time you call

getUserContacts

CodePudding user response:

Your logic of getUserContacts() does not return anything that's why you get undefined. Try to add return as below.

export const getUserContacts = () => {
  const contactDetailsArr = [];
  return db.collection("users").doc(userId).get()
    .then(docs => {
      const contactsObject = docs.data().contacts;
      for (let contact in contactsObject) {
        db.collection("users").doc(contact).get()
          .then(userDetail => {
            contactDetailsArr.push({
              ...
            })
          })
      }
      return contactDetailsArr;
    })
    .catch(err => {
      console.log(err);
    })
}
  • Related