Reputation: 1829
I have this firestore document and I wanted to check if doses
exist in the document since there are other documents that do not have the doses
yet. Hence, retrieving the data inside the doses
will cause an error.
This is how I retrieve the specific document:
useEffect(() => {
const unsubscribe = firestore
.collection("users")
.doc(uid)
.onSnapshot((snapshot) => {
const arr = [];
arr.push({
...snapshot.data(),
});
setUsers(arr);
});
return () => {
unsubscribe();
};
}, []);
To display the data inside the doses
. This will only work if doses
exist in the document. For other users that does not have this object yet, it would cause an error that says:
TypeError: Cannot read property 'selectedVaccine' of undefined
{users && users.map((user) => {
{user.doses.selectedVaccine}
})}
Upvotes: 0
Views: 52
Reputation: 12787
You can use optional chaining
to avoid this issue like this
{user.doses?.selectedVaccine}
Upvotes: 1