React-Native call function inside .then async function

user7639007 picture user7639007 · Mar 1, 2017 · Viewed 9.2k times · Source

I am trying to call a function after the user has taken a picture. I try to do so in the following way:

export default class LA extends Component {
    constructor(props) {
      super(props);
      this.doSomething = this.doSomething.bind(this);
    }


    takePicture() {
      this.camera.capture()
      .then(function(data) {
        doSomething(data.path); //THIS CAUSES THE RUNTIME ERROR
      })
     .catch(err => console.error("error: " + err));
    }

    doSomething(imgPath) {
      console.log(imgPath);
    }


}

And I get the following error when taking a picture:

error: Reference Error: doSomething is not defined

However, If I replace takePicture() with:

takePicture() {
  this.camera.capture()
  .then(function(data) {
    console.log(data.path);
  })
 .catch(err => console.error("error: " + err));
}

The image path is logged, and no error occurs.

Answer

Crysfel picture Crysfel · Mar 1, 2017

You need to use this in order to call a member function. Here's a working example:

export default class LA extends Component {
  constructor(props) {
    super(props);
    this.doSomething = this.doSomething.bind(this);
  }


  takePicture() {
    this.camera.capture()
    .then((data) => {
      this.doSomething(data.path);
    })
   .catch(err => console.error("error: " + err));
  }

  doSomething(imgPath) {
    console.log(imgPath);
  }


}

Note that I've used an arrow function to reference the correct this inside the callback.

Or you can also pass the function directly, like this.

  takePicture() {
    this.camera.capture()
      .then(this.doSomething)
      .catch(err => console.error("error: " + err));
  }

However, the last approach will not run doSomething on the correct scope, for that you will need to bind doSomething to the class, using an arrow function or in the constructor using bind. A third option is to use a decorator to autobind the method using Babel.

Good luck!