So I have this function to store data in Firestore database but I wanted to check if the value exists already and based on that I want to return a boolean.
I kept trying to solve this with async await but it did not seem to work. Finally when I added a return
before performanceRef.get()
, it solved the issue. Even though it solved the issue I'm not clear why. I know it must have something to do with async. Can someone please explain why adding that return solved the issue?
export const createUserPerformanceDocument = async (user, currentDate, answer ) => {
const createdAt = currentDate.toLocaleDateString('en-US');
const performanceRef = firestore.doc(`performance/${user}`);
return performanceRef.get()
.then(doc => {
if(doc.exists) {
const docData = doc.data();
if (docData[createdAt]) {
return false
} else {
try {
performanceRef.set({
[createdAt]: {
Question: answer
}
}, { merge: true })
return true
} catch(error) {
console.log('Error creating performance data!', error.message);
return false
}
}
} else {
console.log("This user does not exist in the database");
}
})
}