Search code examples
javascriptreactjsfirebasereact-nativegoogle-cloud-firestore

My filtered data keeps returning data it shouldn't return


I'm trying to filter blocked users from a list of chats. It returns the correct list when I use "===" to display users that are blocked. But when I use "!==", it returns users that aren't blocked and users that are blocked. It only excludes one blocked user and returns the rest. What can I do?

Here's my code...

const checkBlockedUsers = async () => {
    const blockedUsersList:any = []
    const blockedUsersRef = collection(db, `users`, auth.currentUser?.uid, `blockedUsers`)
    getDocs(blockedUsersRef).then(blockedUsers => {
      blockedUsers.docs.map(blockedUser => {
        blockedUsersList.push(blockedUser.data().blockedUser.id)
      })
    }).then(() => {
      blockedUsersList.map(blockedUserId => {
            onSnapshot(query(collection(db, `convos`, convoId, `chats`), orderBy(`timestamp`, `asc`)), snapshot => {
              const filteredData = snapshot.docs.filter(doc => doc.data().user.id === blockedUserId)
              filteredData.map(doc => {
                console.log(doc.data().user.username)
              })
            }) 

          }
        )
    })
    
  }

I want it to exclude all blocked users from the list of chats. And not exclude just one blocked user


Solution

  • you're making so many asynchronous calls inside a loop, and by the time the callbacks within the loop executed, the loop may have been already completed.

    1. To fix this use await so that each function runs one after another to get proceeded.

    2. I used Array.includes to filter the chats to see if the user is in the blocked users list

    const checkBlockedUsers = async () => {
     try {
       const blockedUsersList = [];
    
       const blockedUsersRef = collection(db, 'users', auth.currentUser?.uid, 'blockedUsers');
       const blockedUsersSnapshot = await getDocs(blockedUsersRef);
    
       blockedUsersSnapshot.forEach((blockedUser) => {
         blockedUsersList.push(blockedUser.data().blockedUser.id);
       });
    
       const chatsRef = query(collection(db, 'convos', convoId, 'chats'), orderBy('timestamp', 'asc'));
       const chatsSnapshot = await getDocs(chatsRef);
    
       const filteredChats = chatsSnapshot.docs.filter((doc) => {
         return !blockedUsersList.includes(doc.data().user.id);
       });
    
       filteredChats.forEach((doc) => {
         console.log(doc.data().user.username);
       });
     } catch (error) {
       console.error('Error:', error);
     }
    };
    

    Hope this works Thanks.