array.prototype..forEach function skipped with values in variable

huangapple go评论65阅读模式
英文:

array.prototype..forEach function skipped with values in variable

问题

我有一个问题,我有一个与我的React.JS项目连接的Firebase Firestore数据库,用户可以报名课程。现在,如果我尝试从数据库中加载用户集合,它只返回1个条目。

但是,当我尝试使用array.prototype.map对其进行循环时,它总是跳过它。

我通过函数进行了调试,并发现Firestore 返回的docs包含我想要接收的值。

Firestore返回的数据

我不知道为什么它不起作用。任何想法或帮助都将不胜感激。

英文:

I have a problem, i have a Firebase Firestore Database connected to my React.JS Project, where users can enroll to courses. Now if i'm trying to load the users collection from the DB it returns 1 entry.

    const fetchAthletes = async () => {
        debugger
        try {
            const athletes: Array<any> = [];
            const athleteRef = collection(db, COLLECTION_NAME_ATHLETE);
            const getAthleteQuery = query(athleteRef, where('user', '==', userAuthToken.accessToken));
            const querySnapshot = await getDocs(getAthleteQuery)
            if (querySnapshot.docs) {
                //this for each gets skipped, even when querySnapshot.doc has values in it
                querySnapshot.forEach((doc) => {
                    athletes.push({
                        id: doc.id,
                        ...doc.data()
                    });
                    setAthletes(athletes as Array<Athlete>);
                })
            }
        } catch (error: unknown) {
            enqueueSnackbar((error as string), { variant: 'error', autoHideDuration: 3000 })
        }
    }

But when i want to loop over it via array.prototype.map it always skips it.

I debbuged through the funtion and found out that docs from Firestore is set with values tbat i wanna recieve.

Data returned by Firestore

I have no clue why it doesn't work. Any idea or help is appreciated

答案1

得分: 0

不要尝试单独设置每个文档的状态,而是建立一个数组并将整个数组设置为状态。

const querySnapshot = await getDocs(getAthleteQuery);
setAthletes(querySnapshot.docs.map((doc) => ({
  id: doc.id,
  ...doc.data(),
}));
英文:

Rather than attempt to individually set each doc into state, build up your array and set the entire thing into state

const querySnapshot = await getDocs(getAthleteQuery);
setAthletes(querySnapshot.docs.map((doc) => ({
  id: doc.id,
  ...doc.data(),
}));

huangapple
  • 本文由 发表于 2023年2月6日 05:15:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定