I'm an amateur at JS and was having this problem. I am making a chat app and I'm querying firebase firestore to check if a chat exists with a person with a particular email. Hence I am using a function call chatExists() and am passing in the email that I want to look up.
The problem is that the querying works fine and everything goes well, even the console.log() statements work but I cannot seem to get a value from the "return" statement. I want to return a boolean value, so that I can put it in an if statement and then take necessary actions based on whether or not the chat exists.
I tried looking at other problems at StackOverflow but I could not understand them. It would really mean a lot if anyone would tell me exactly what I'm doing wrong and exactly how I could fix this problem. If it's required to change a lot of the code I'd be really happy if someone would write that code out for me because this is a hobby project I'm building on my own and I can't really find any sort of help. Thanks in advance!
const chatExists = async (recipientEmail) => {
try {
const collectionRef = collection(db, "chats");
const chatQuery = query(
collectionRef,
where("users", "array-contains", user.email)
);
const chatQuerySnapshot = await getDocs(chatQuery);
chatQuerySnapshot.forEach((doc) => {
if (doc.data().users.includes(recipientEmail)) {
console.log("Contact exists");
return true;
} else {
console.log("Contact does not exist");
return false;
}
});
} catch {
(err) => {
console.log(err);
};
}
};