I'm a little stuck developing my application. So far im able to connect to the Firestore db and get my documents. My plan is to fetch the data from each document and store it in an array. From there i will display it.
The issue im having is that the results from the first time render wont add the elements to the array. DATA.push() method works but its not saved outside of this forEach loop? Thanks!
const data is where the document ref is stored.
const DATA = [] is the array.
const [data, setdata]= useState([{}]);
useEffect(() => {
const getUsers = async () => {
const data = await getDocs(usersCollectionRef);
data.forEach(doc =>{
DATA.push({id: doc.id, title: doc.data().Type, status: doc.data().status, location: doc.data().Location, type: doc.data().Type, injured: doc.data().Injured, collar: doc.data().Collar, color: doc.data().Colour })
})
};
getUsers();
console.log(dataNew);
}, []);
const DATA = [];
CodePudding user response:
You can just map data from all documents in an array, set that in state and render it. Try refactoring the code as shown below:
const [data, setData]= useState([]);
useEffect(() => {
const getUsers = async () => {
const snapshot = await getDocs(usersCollectionRef);
const data = snapshot.docs.maps(d => ({ id: d.id, ...d.data() }))
console.log(data);
setData(data);
};
getUsers();
}, []);
return(
<div>
{
data.map((d) => {
<p>{ d.id }</p>
})
}
</div>
)