Reputation: 31
I have created data for firestore.But it gives empty array.And it renders two times at the one time and it gives first empty array and second is data object.I have also used useMemo. Here is a data model of firestore:
And my code :
const [posts, setPosts] = useState([]);
useEffect(() => {
db.collection("posts").onSnapshot((snapshot) =>
snapshot.docs.map((doc) => setPosts({ id: doc.id, data: doc.data() }))
);
}, []);
Upvotes: 0
Views: 230
Reputation: 452
Try this solution. You have to temporarily push the posts to an array inside you function, and then set that array to posts
.
const [posts, setPosts] = useState([]);
function fetchPosts() {
const docList = [];
firebase
.firestore()
.collection("posts")
.onSnapshot((snapshot) => {
snapshot.forEach((doc) => {
docList.push({
id: doc.id
data: doc.data()
});
});
setPosts(docList);
});
}
useEffect(() => {
fetchPosts()
}, [])
Upvotes: 1