1
  teste(){
   console.log('a');
  }

 componentDidMount() {
   // firebase things?
   firebase.database().ref('Matheus').on('value', function(snapshot){
     itens = snapshot.val();
     itens.forEach((data) => {
     firebase.storage().ref(data).getDownloadURL().then(this.teste);
   });
 });

Code works. It is only impossible to call the function this.teste

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99

1 Answers1

2

The context of this has changed when running inside the inner function.
Either store this in a temp variable to use it inside the function:

 componentDidMount() {
    const that = this; // holding the context for this
   // firebase things?
   firebase.database().ref('Matheus').on('value', function(snapshot){
     itens = snapshot.val();
     itens.forEach((data) => {
     firebase.storage().ref(data).getDownloadURL().then(that.teste); // using that instead of this
   });
 });

Or use an arrow function which will use a lexical context for this:

 componentDidMount() {
    const that = this; // holding the context for this
   // firebase things?
   firebase.database().ref('Matheus').on('value', (snapshot) => { // arrow function instead
     itens = snapshot.val();
     itens.forEach((data) => {
     firebase.storage().ref(data).getDownloadURL().then(that.teste);
   });
 });
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99