英文:
array.prototype..forEach function skipped with values in variable
问题
我有一个问题,我有一个与我的React.JS项目连接的Firebase Firestore数据库,用户可以报名课程。现在,如果我尝试从数据库中加载用户集合,它只返回1个条目。
但是,当我尝试使用array.prototype.map
对其进行循环时,它总是跳过它。
我通过函数进行了调试,并发现Firestore 返回的docs
包含我想要接收的值。
我不知道为什么它不起作用。任何想法或帮助都将不胜感激。
英文:
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.
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(),
}));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论