Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using catch() with a .on() in firebase

I am retrieving data in firebase using the following code:

  this.managerList = this.afDB.database.ref('users').orderByChild('managedby').equalTo(uID);
      this.managerList.on('value', (snapshot) => {
        this.managerIdArray = Object.keys(snapshot.val());
        this.managerNameArray = snapshot.val();
       });

Whenever a null value is returned, I get an error : Error: Uncaught (in promise): TypeError: Cannot read property............ of undefined.

When I try to add a catch() to the above, it says cannot use catch() or then(). How do I use a catch() to take error.

like image 214
user165242 Avatar asked Dec 18 '22 03:12

user165242


1 Answers

Firebase's on() method attaches a listener to the data, which then fires once with the current value and each time the value changes. This means your callback can get called multiple times. Since a promise can only resolve or fail once, on does not return a promise.

It looks like your query does not return any result right now, so snapshot.val() returns null. And then Object.keys(null) throws an error. So something like this is closer:

this.managerList = this.afDB.database.ref('users').orderByChild('managedby').equalTo(uID);
this.managerList.on('value', (snapshot) => {
  if (snapshot.exists()) {
    this.managerIdArray = Object.keys(snapshot.val());
    this.managerNameArray = snapshot.val();
  };
});
like image 131
Frank van Puffelen Avatar answered Dec 28 '22 11:12

Frank van Puffelen