karim
karim

Reputation: 25

Check if data exist in Firebase database with Angular

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;
});  
}

Upvotes: 0

Views: 1322

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599061

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:

Upvotes: 1

Related Questions