我如何避免在我的querysnapshot.foreach上循环? [英] How i can avoid the loop on my querysnapshot.foreach?

查看:37
本文介绍了我如何避免在我的querysnapshot.foreach上循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户有2个团队:

  • 丹斯
  • 柔道

在我的子集合"membersList" 中,团队Danse有1个好友请求,而Judo没有.

On my subcollection "membersList" the team Danse had 1 friend request and Judo had none.

所以我想我的屏幕上只有一个请求.但是当我有2个或更多团队时,一会儿继续循环播放,并且请求与团队数一起出现.

So I'm suppose to have just one request on my screen. But when I have 2 or more teams, the while continue to loop and the request appear with the numbers of team.

我认为问题出在我的 querySnaphost.forEach 上,但在我的控制台上,他给我返回了文档不为空的文档(因此,团队danse)和另一个未找到文档的文档.

I think the problem is on my querySnaphost.forEach but on my console he return me the doc not empty (so the team danse ) and an other one with document not found.

let fetch = async () => {
    firestore()
      .collection("Teams")
      .where("uid", "==", await AsyncStorage.getItem("userID"))
      .get()
      .then((querySnapshot) => {
        if (querySnapshot.empty) {
          console.log("no documents found");
        } else {
          querySnapshot.forEach((doc) => {
            let Teams = doc._data;
            console.log(Teams);
            updateActivity((arr) => [...arr, Teams]);
            console.log(Activity);

            doc.ref
              .collection("membersList")
              .where("statut", "==", "en attente")
              .get()
              .then((querySnapshot) => {
                if (querySnapshot.empty) {
                  console.log("no documents found cc");
                } else {
                  querySnapshot.forEach((doc) => {
                    let members = doc._data;
                    console.log("aa", members);
                    updateMembersList((arr) => [...arr, members]);
                    console.log("cc", MembersList);
                  });
                }
              });
          });
        }
      });
  };
  useEffect(() => {
    fetch();
  }, []);

以下是调用 fetch()时记录的内容:

Here is what is logged when fetch() is called:

{"Activity": "Danse", "Adress": "Plage", "City": "Nice", "Owner": true, "members": "3", "text": "bouh", "tokenTeam": "n5ounxsf2bq", "uid": "PTbEn2fba0QudXI8JE8RioQ9of53"}
[]
no documents found cc

推荐答案

您不应将函数命名为 fetch ,因为这是

You should not name your function fetch as this is a reserved global function which you should treat like undefined - don't assign anything to it. I recommend also using const over let where applicable.

注意::此答案使用了此答案中所述的相同策略.

Note: This answer makes use of the same strategy described in this answer.

const fetchMemberRequests = async () => {
  const userTeamsQuerySnapshot = await firestore()
    .collection("Teams")
    .where("uid", "==", await AsyncStorage.getItem("userID"))
    .get();

  if (userTeamsQuerySnapshot.empty) {
    console.log("User owns no teams.");

    // empty Activity & MembersLists
    updateActivity([]);
    updateMembersList([]);
    return;
  }
  
  // for each team, fetch the pending requests and return a { team, memberRequests } object
  const fetchMemberRequestsPromises = userTeamsQuerySnapshot.docs
    .map(async (teamDocSnapshot) => {
      const teamData = teamDocSnapshot.data();
      
      const memberRequestsQuerySnapshot = await teamDocSnapshot.ref
        .collection("membersList")
        .where("statut", "==", "en attente")
        .get();
        
      if (memberRequestsQuerySnapshot.empty) {
        console.log(`Activity ${teamData.Activity} has no pending requests.`);
        return {
          team: teamData,
          memberRequests: []
        }
      }
      
      const memberRequestsArray = memberRequestsQuerySnapshot.docs
        .map((memberRequestDocSnapshot) => memberRequestDocSnapshot.data());
        
      console.log(`Activity ${teamData.Activity} has ${memberRequestsArray.length} pending requests.`);
      return {
        team: teamData,
        memberRequests: memberRequestsArray
      }
    });
    
  const memberRequests = await Promise.all(fetchMemberRequestsPromises);
  
  // memberRequests is an array of { team: teamData, memberRequests: arrayOfMembers }
  // which could be used to show the requests in groups
  
  // these lines replicate your current code:
  const allTeams = [];
  const allMemberRequests = [];
  for (const request of memberRequests) {
    allTeams.push(request.team);
    allMemberRequests.push(...request.memberRequests); // note: spreads array
  }
  
  console.log(`User owns ${allTeams.length} teams, with a total of ${allMemberRequests.length} pending requests.`);
  
  // replace Activity and MembersList rather than append to them
  updateActivity(allTeams);
  updateMembersList(allMemberRequests);
}

这篇关于我如何避免在我的querysnapshot.foreach上循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆