I am trying to read in from a Firebase realtime db (JS) to check if a class name already exists under the user's branch. If this class exists, the user should not be able to add a duplicate class (and the placeholder would = "Please enter a unique name" [in the else if of saveAndMakeClass() below]). When checking if the class exists in the doesClassExist(className) method, the console.log("true") check runs correctly, signifying that the class exists, but nothing is returned, and in saveAndMakeClass(), doesClassExist(text) is undefined. How can I get doesClassExist(text) to be true instead of undefined like the console.log statement?
Here is a screenshot of what doesClassExist(text) prints as (undefined) while the console.log within doesClassExist(text) prints as true: supporting screenshot
Here is the saveAndMakeClass() function (that has doesClassExist(text) as undefined instead of true):
function saveAndMakeClass(){ //submit button
var text = document.getElementById('enterBurrowName').value;
console.log("RESULT OF DOESCLASSEXIST(TEXT): " + doesClassExist(text));
if(text == "" || text == " "){
document.getElementById('enterBurrowName').placeholder = "Please enter a valid name";
resetColorAndImg();
}else if(doesClassExist(text)){
document.getElementById('enterBurrowName').value = "";
document.getElementById('enterBurrowName').placeholder = "Please enter a unique name";
resetColorAndImg();
}else{ //get rid of ".", "#", "$", "[", or "]"
document.getElementById('enterBurrowName').value = "";
var classCode = createClassCode();
createClassCard(text, currentColor, currentSquirrel);
cancelSubmitNewClass();
resetColorAndImg();
updateUserData(text, currentColor, currentSquirrel, classCode); // 1st Time use
}
}
Here is the doesClassExist(text) method (that does not return true but prints it):
function doesClassExist(nameClass){
const dbRef = ref(getDatabase());
get(child(dbRef, '/'+auth.currentUser.uid+'/Details/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach((childSnapshot) => {
if(childSnapshot.key == nameClass){
console.log("true");
return true;
}
// console.log(childSnapshot.key, childSnapshot.val());
});
// return false;
return false;
// console.log(snapshot.val());
// console.log(snapshot.val().Details);
} else {
console.log("No data available");
return false;
// return false;
}
}).catch((error) => {
console.error(error);
// return false;
return false;
});
}
Here is the current Firebase structure ("chicken" would be the class name being accessed in this case):
I am new to Firebase and its methods, so any feedback is greatly appreciated! Thank you so much for taking the time to read all of this!