[英]How do I get all documents in a Cloud Firestore collection using Version 9 of the Modular Web SDK?
I am trying to get all documents in a collection using version 9 of the Web SDK. But I am getting this error:我正在尝试使用 Web SDK 的版本 9 获取集合中的所有文档。但我收到此错误:
"TypeError: querySnapshot.map is not a function"
“类型错误:querySnapshot.map 不是函数”
This is the component where I get the error:这是我收到错误的组件:
import { useEffect, useState } from "react";
import { collection, getDocs } from "firebase/firestore";
import { db } from "../../firebase";
function CurrentUser() {
const [names, setNames] = useState([]);
async function getMakers() {
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.map((doc) => {
setNames((doc.id = doc.data()));
});
}
getMakers();
return <div>{names.map((doc) => doc.firstName)}</div>;
}
export default CurrentUser;
querySnapshot
is an instance of a QuerySnapshot
object, not a JavaScript Array. querySnapshot
是QuerySnapshot
object 的实例,而不是 JavaScript 数组。 This means it doesn't have the normal Array methods like map()
, some()
and includes()
.这意味着它没有普通的 Array 方法,如
map()
、 some()
和includes()
。 However, it does have its own version of a forEach()
method that can be used to iterate over the entries in the snapshot.但是,它确实有自己的
forEach()
方法版本,可用于迭代快照中的条目。 If you need to access methods of a normal array, you can use the snapshot's docs
property instead (which internally calls forEach()
to assemble an array).如果您需要访问普通数组的方法,则可以改用快照的
docs
属性(它在内部调用forEach()
来组装一个数组)。
To correctly fetch the documents in the array, optionally plucking the first names of each returned document, you can use any of the following strategies:要正确获取数组中的文档,可选择提取每个返回文档的名字,您可以使用以下任何策略:
useState
and useEffect
for each user's complete datauseState
和useEffect
对每个用户的完整数据import { useEffect, useState } from "react";
// ...
const [userDataArray, setUserDataArray] = useState([]);
useEffect(() => {
let unsubscribed = false;
getDocs(collection(db, "users"))
.then((querySnapshot) => {
if (unsubscribed) return; // unsubscribed? do nothing.
const newUserDataArray = querySnapshot.docs
.map((doc) => ({ ...doc.data(), id: doc.id }));
setUserDataArray(newUserDataArray);
})
.catch((err) => {
if (unsubscribed) return; // unsubscribed? do nothing.
// TODO: Handle errors
console.error("Failed to retrieve data", err);
});
return () => unsubscribed = true;
}, []);
return (
<div>
{ userDataArray.map((userData) => userData.firstName) }
</div>
);
useState
and useEffect
for just each user's firstName
firstName
使用useState
和useEffect
import { useEffect, useState } from "react";
// ...
const [firstNamesArray, setFirstNamesArray] = useState([]);
useEffect(() => {
let unsubscribed = false;
getDocs(collection(db, "users"))
.then((querySnapshot) => {
if (unsubscribed) return; // unsubscribed? do nothing.
const newFirstNamesArray = querySnapshot.docs
.map((doc) => doc.get("firstName"));
setFirstNamesArray(newFirstNamesArray);
// need to remove duplicates? use this instead:
// const firstNamesSet = new Set();
// querySnapshot
// .forEach((doc) => firstNamesSet.add(doc.get("firstName")));
//
// setFirstNamesArray([...firstNamesSet]);
})
.catch((err) => {
if (unsubscribed) return; // unsubscribed? do nothing.
// TODO: Handle errors
console.error("Failed to retrieve data", err);
});
return () => unsubscribed = true;
}, []);
return (
<div>
{ firstNamesArray }
</div>
);
react-use
to handle intermediate states.react-use
这样的 tree-shakeable 实用程序库来处理中间状态。import { useAsync } from 'react-use';
// ...
const remoteUserData = useAsync(
() => getDocs(collection(db, "users"))
);
if (remoteUserData.loading)
return (<div>Loading...</div>);
if (remoteUserData.error) {
console.error("Failed to load data! ", remoteUserData.error);
return (<div class="error">Failed to load data!</div>);
}
const userDataArray = remoteUserData.value;
return (
<div>
{ userDataArray.map((userData) => userData.firstName) }
</div>
);
useEffect(() => onSnapshot(collection(db, 'posts'), snapshot => { setPosts( snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })) ) }), [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.