Firebase version 9.6.9
I'm using onSnapshot function to get the data from the firestore.
Code:
const [posts, setPosts] = useState([])
useEffect(() => {
return onSnapshot(
query(collection(db, 'posts'), orderBy('timestamp', 'desc')),
(snapshot) => {
console.log(snapshot.docs)
}
)
}, [db])
snapshot.docs logs a metadata and not the data I need (the posts collection).
CodePudding user response:
The snapshot.docs
is an array of QueryDocumentSnapshot. You can get data from your documents, by using .data()
method on every snapshot as shown below:
return onSnapshot(
query(collection(db, 'posts'), orderBy('timestamp', 'desc')),
(snapshot) => {
const result = snapshot.docs.map((d) => ({
id: d.id,
...d.data()
}))
console.log('>>> Documents', result)
}
)
The metadata
has some information about the snapshots such as the source.