0

i am trying to fetch chatList from firebase and for each chat, get username from users doc, but the array stored in the chats state is not iterating...

and if i remove await from the query which fetches name of freind then this chats is iterable but in this case, value of temp or freind property of chats / chatList is undefined

const Chat = () => {
  const { currentUser } = useAuth();
  const [chats, setChats] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const chatListQuery = firestore()
      .collection('chatRoom')
      .where('members', 'array-contains', currentUser.uid)
      .where('group', '==', false)
      .orderBy('recentMessage.sendAt', 'desc');
    const unsubscribe =
      chatListQuery.onSnapshot((querySnapShot) => {
        const chatList = []

        querySnapShot.forEach(async (item) => {

          const temp = [];
          const freindId = item.data().members.filter((member) => member !== currentUser.uid);

          await firestore().collection('users').doc(freindId[0]).get().then((snapshot) => {
            temp.push(
              snapshot.data().name,
            );
            // setFreind(snapshot.data().name)
          });

          chatList.push({ ...item.data(), id: item.id, freind: temp });
        });
        setLoading(false)
        setChats(chatList)
      });


    return () => unsubscribe()
  }, [])

  return (
    <View>
      {loading ? (
        <Text>Loading...</Text>
      ) : (
        <>
          {console.log(typeof chats)}
          {/* 
          above log displays this but either `chats.map` or `FlatList` is not iterating over this 
          []
          0: {timestamp: FirestoreTimestamp, group: false, members: Array(2), recentMessage: {…}, id: '5h4N0KcE6KYLiDA4esNv', …}
          1: {group: false, timestamp: FirestoreTimestamp, members: Array(2), recentMessage: {…}, id: 'RB9EIedrr4vp3JyGSmUa', …}
          2: {timestamp: FirestoreTimestamp, group: false, members: Array(2), recentMessage: {…}, id: 'LapcO2Zc0Qv4Kyx7jeiu', …}
          3: {group: false, timestamp: FirestoreTimestamp, members: Array(2), recentMessage: {…}, id: 'h1i8lTbPmnbZTgG2mwDV', …}
          length: 4
          [[Prototype]]: Array(0)
          */}

          <FlatList data={chats} renderItem={({ item }) => <Text>{item.freind}</Text>} keyExtractor={item => item.id} />
        </>
      )}
    </View>
  )
}

export default Chat;

below is the log value of chats when using await

[]
0: {timestamp: FirestoreTimestamp, group: false, members: Array(2), recentMessage: {…}, id: '5h4N0KcE6KYLiDA4esNv', …}
1: {group: false, timestamp: FirestoreTimestamp, members: Array(2), recentMessage: {…}, id: 'RB9EIedrr4vp3JyGSmUa', …}
2: {timestamp: FirestoreTimestamp, group: false, members: Array(2), recentMessage: {…}, id: 'LapcO2Zc0Qv4Kyx7jeiu', …}
3: {group: false, timestamp: FirestoreTimestamp, members: Array(2), recentMessage: {…}, id: 'h1i8lTbPmnbZTgG2mwDV', …}
length: 4
[[Prototype]]: Array(0)

below is the log value of chats when i do not use async/await

(4) [{…}, {…}, {…}, {…}]
0: {timestamp: FirestoreTimestamp, group: false, members: Array(2), recentMessage: {…}, id: '5h4N0KcE6KYLiDA4esNv', …}
1: {group: false, timestamp: FirestoreTimestamp, members: Array(2), recentMessage: {…}, id: 'RB9EIedrr4vp3JyGSmUa', …}
2: {timestamp: FirestoreTimestamp, group: false, members: Array(2), recentMessage: {…}, id: 'LapcO2Zc0Qv4Kyx7jeiu', …}
3: {group: false, timestamp: FirestoreTimestamp, members: Array(2), recentMessage: {…}, id: 'h1i8lTbPmnbZTgG2mwDV', …}
length: 4
[[Prototype]]: Array(0)

but in this case, value of item.freind[0] is undefined

2 Answers 2

1

Try to use this useEffect code

useEffect(() => {

    const chatListQuery = firestore()
        .collection('chatRoom')
        .where('members', 'array-contains', currentUser.uid)
        .where('group', '==', false)
        .orderBy('recentMessage.sendAt', 'desc');

    const unsubscribe =
        chatListQuery.onSnapshot((querySnapShot) => {

            const queryPromises = querySnapShot.docs.map((item) => {
                return new Promise((resolve,reject) => {

                    const temp = [];
                    const freindId = item.data().members.filter((member) => member !== currentUser.uid);

                    firestore().collection('users').doc(freindId[0]).get().then((snapshot) => {
                        temp.push(snapshot.data().name);
                        resolve({
                            ...item.data(), id: item.id, freind: temp
                        })
                    });
                })
            })

            Promise
                .all(queryPromises)
                .then(chatsData => {
                    setChats(chatsData)
                })
                .finally(() => {
                    setLoading(false)
                })
        });

    return () => unsubscribe()
}, [])
Sign up to request clarification or add additional context in comments.

1 Comment

got it, but there is a slight correction there should be querySnapShot.docs.map instead of querySnapShot.map. I also tried promises but your finally block nailed it...Thanks
1

Alternate Solution:

useEffect(() => {
    const chatListQuery = firestore()
      .collection('chatRoom')
      .where('members', 'array-contains', currentUser.uid)
      .where('group', '==', false)
      .orderBy('recentMessage.sendAt', 'desc');
    const unsubscribe =
      chatListQuery.onSnapshot((querySnapShot) => {
        const chatList = []
        const promises = [];
        const freindList = []

        querySnapShot.forEach((doc) => {
          const freindId = doc.data().members.filter((member) => member !== currentUser.uid);
          const promise = firestore().collection('users').doc(freindId[0]).get().then((snapshot) => {
            freindList[doc.id] = snapshot.data().name;
          });
          promises.push(promise);
          chatList.push({ ...doc.data(), id: doc.id, freind: null })
        })

        Promise.all(promises).then(() => {
          setChats(chatList.map(chat => {
            console.log(freindList[chat.id])
            return { ...chat, name: freindList[chat.id] }
          }))
        });
        setLoading(false)
      });

    return () => unsubscribe()
  }, [])```

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.