ChrisCv
ChrisCv

Reputation: 17

Return snapshot value Firebase

I'm new in Firebase and Typrescript. I have the following problem: I want the username of a user from the realtime database.

  getUsername(id){
    var username
    firebase.database().ref().child("users/"+id+"/username")
    .once("value",snapshot => {
      if (snapshot.exists()){
        username = snapshot.val();
        console.log("IN"+username)      
      }
    });
    console.log("OUT"+username)
    return username
  }

The problem is that outside the if() the username is undefined. I read that with firebase you have to work asynchronously, so I followed this guide: How do I return a snapshot.val() from Firebase to a variable? so I created the functions:

   getListings(id) {
    return firebase.database().ref().child("users/"+id+"/username").once("value");
  }
  
   loadListing(id){
    this.getListings(id).then(this. setListing, this.showError);
}

   setListing(snapshot){
      this.currentSnapshot = snapshot.val()
  }
  
   showError(e){
      console.log(e);
  }
  
   init(id){
      this.loadListing(id);
  }

and in other page I call init:

export class ProfilePage implements OnInit {
  username : any;
  constructor(private route: ActivatedRoute, private router: Router, public authService: AuthenticationService) {};
  
  ngOnInit() {
    this.authService.init(this.authService.userData.uid)
    console.log(this.authService.currentSnapshot)
  }
}

but i receive the error:

Error: Uncaught (in promise): TypeError: Cannot set property 'currentSnapshot' of undefined

Can anyone help me ?

Upvotes: 0

Views: 301

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

I suspect that the this in your setListing function is no longer referring to the object you expect.

If that is the cause, you might be able to fix it by binding it to the correct object:

this.getListings(id).then(this.setListing.bind(this));

Upvotes: 1

Related Questions