Issue
Using typescript I get
QueryDocumentSnapshot<DocumentData>.data(options?: SnapshotOptions | undefined): DocumentData
The question is.. Do I really have to check if data is possibly undefined
if (snapDoc.data()) //...
else //...
or it is safe to do snapDoc.data()! for the fact that the data can never be undefined?
If it can be undefined then when or at what case does the data will return undefined?
Solution
If you are querying a single document using getDoc(<DoucmentReference>) that returns a DocumentSnapshot then yes, data() will return undefined if that document does not exist.
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
If you are querying multiple documents using getDocs(<query>), a QuerySnapshot is returned that has .docs property (array of QueryDocumentSnapshot) that contains all matched documents that exist for sure. So .data() will never be undefined in that case as mentioned in the documentation.
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
If it can be undefined then when or at what case does the data will return undefined?
In short, data() can return undefined if you are using it on a DocumentSnapshot when you fetch a single document using getDoc()
Answered By - Dharmaraj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.