skip to Main Content

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


  1. Chosen as BEST ANSWER

    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()
      }, [])```
    

  2. 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()
    }, [])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search