0

I want to collect the UIDs to the Array fields in Firestore. Successfully fetched each user data, however, I can't list.

contactArray: {"0": "xxxxxxxxxxxx", "1": "yyyyyyyyyyyy"}

User data can be retrieved, but the problem cannot be displayed as a list. I could push it, but it disappears for some reason.

The warning:

Expected to return a value in arrow function

useEffect

const [contactList, setContactList] = useState([])

useEffect(() => {
  if (currentUserUid) {
    firestore.doc(`users/${currentUserUid}`).get().then(userSnapshot => {
      const { contactUidList } = userSnapshot.data()
      return contactUidList
    })
      .then((contactUidList) => {
        contactUidList.map((contactUid) => {
          firestore.doc(`users/${contactUid}`)
            .onSnapshot(userQuerySnapshot => {
              contactList.push(userQuerySnapshot.data())
              setContactList(contactList)
            })
        })
      })
  }
}, [currentUserUid, contactList])

View

  return (
    <ul>
      {contactList.map((contact, idx) => {
          return(<p>{contact.name}</p>)
       ))
  )
k10a
  • 947
  • 2
  • 11
  • 30
  • To get rid of that warning, you'll either want to remove the `=>` in `.then((contactUidList) => {` or return something (it doesn't really matter what) at the end of that callback. – Frank van Puffelen Jun 01 '20 at 18:15

1 Answers1

0

Data is loaded from Firestore (and most cloud APIs) asynchronously. For that reason you'll need to keep contactList in the state, and update it there. When you do that, React knows to update the UI when the results come back from the database (or are updated).

So something like:

const [contactList, setContactList] = useState(0);
useEffect(() => {
  if (currentUserUid) {
    firestore.doc(`users/${currentUserUid}`).get().then(userSnapshot => {
      const { contactArray } = userSnapshot.data()
      return contactArray
    })
      .then((contactArray) => {
        contactUidList.map((contactUid) => {
          firestore.doc(`users/${contactUid}`)
            .onSnapshot(userQuerySnapshot => {
              contactList.push(userQuerySnapshot.data())
              setContactList(contactList)
            })
        })
      })
  }
}, [currentUserUid, contactList])
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you so much! I have been successfully fetched `contactList`. But it has not been displayed yet... – k10a Jun 01 '20 at 16:32