I'm trying to fetch all data of documents inside the collection but unfortunately the code only fetch data of one single document.
const Charities = ({navigation}) => {
const [userData, setUserData] = useState([]);
{/*fetch all documents from firestore*/}
const fetchData = async()=>{
const querySnapshot = await getDocs(collection(db, "Charities"));
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
setUserData(doc.data())
});
}
useEffect(() => {
fetchData()
},[])
function renderBody(){
return(
<View
style={{
// paddingBottom:100,
marginTop:10,
height:300,
alignItems:'center',
justifyContent:'center'
}}>
<Text>{userData?.Name}</Text>
</View>
)
}
}
Between the code of fetching document from the official firebase website which only retrieve the info of the one document instead of all documents. So, I want the code to fetch all data of all documents that is what I'm expected. Your help is highly appreciated.
You are logging each document to the console with forEach, but you are assigning a new doc.data to the same state each time. Instead, you can push each doc.data into an array and then update the state with the whole array.
const fetchData = async () => {
const querySnapshot = await getDocs(collection(db, "Charities"));
const data = [];
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
data.push(doc.data());
});
setUserData(data);
};
//or
const fetchData = async () => {
const querySnapshot = await getDocs(collection(db, "Charities"));
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
setUserData(prevData => [...prevData, doc.data()]);
});
};