2

I'm already using react es6 but still in this case, I don't know how to avoid using that for this:

const that = this;

UploadApi.exec(file).then(data => {
    that.setState({ loading : false});
});
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Alex Yong
  • 7,425
  • 8
  • 24
  • 41

2 Answers2

6

In this example, you are already using arrow function, so storing the reference in a separate variable is not required. You can directly use this keyword like this:

//const that = this;

UploadApi.exec(file).then(data => {
    this.setState({ loading : false});
});

Storing the reference in a separate variable required, when you use callback method like this:

const that = this;

UploadApi.exec(file).then(function(data){
    that.setState({ loading : false});
});

But, you can avoid the extra variable by using .bind(this) with callback method, like this:

//const that = this;

UploadApi.exec(file).then(function(data){
    this.setState({ loading : false});
}.bind(this));

Check this answer for complete detail, arrow function vs function declaration

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
0

You need to create yout UploadApi.exec that way so that after transpiling your javascript get created accordingly..like below

In you UploadApi

exec=(file:any):Q.Promise=>{

}

and then use it like below

UploadApi.exec(file).then(data => {
    this.setState({ loading : false});
});
Rishi Tiwari
  • 1,041
  • 1
  • 10
  • 20