0

I'm working on web project with Angular connected with Firebase console and I used this function defined in my service class to verify if the value exists in the database before saving, When I call this function in my component I usually get undefined value.

This is my service function :

  ifExist(category : CategoryType){
    firebase.database().ref("/categories/").child("categories").orderByChild("category_name").equalTo(category.category_name)
.once( "value" , snapshot => {
  if (snapshot.exists()){
    const userData = snapshot.val();
    console.log("exists!", userData);
    return true;
  }
  return false;
});  
}
halfer
  • 19,824
  • 17
  • 99
  • 186
karim
  • 25
  • 5
  • 1
    Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Jul 13 '20 at 08:50
  • So did the answer work for you? – Vega Jul 14 '20 at 19:41
  • Why did you accept it then? – Vega Jul 15 '20 at 09:42

1 Answers1

1

Data is loaded from Firebase asynchronously. Your return false runs before your if (snapshot.exists()){ is called, so you'll always return false.

The solution is to return a promise:

ifExist(category: CategoryType) {
  return firebase.database().ref("/categories/").child("categories")
    .orderByChild("category_name").equalTo(category.category_name)
    .once("value", snapshot => {
      if (snapshot.exists()) {
        const userData = snapshot.val();
        console.log("exists!", userData);
        return true;
      }
      return false;
    });
}

And the use that when calling the function, either with:

ifExist(yourCategoryType).then((result) => {
  console.log("ifExist returned "+result);
});

Or with more modern async / await:

const result = await ifExist(yourCategoryType)
console.log("ifExist returned "+result);

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807