cocool97
cocool97

Reputation: 1251

'this' is undefined - ReactJS

I'm building a reactJS code, which is the following code. It was working until I add the this.requestCSVDownload() function call into my then function.

async handleMerging(){
    console.log("merging launched...")

    this.launchMerging({
      userId: this.state.userId,
      noteId: this.state.noteId,
      type: this.state.type,
      dateUser: this.state.content
    });

    var intervalId = await setInterval(()=> {
      this.requestPercentage({
          userId: this.state.userId,
          noteId: this.state.noteId
      }).then(async result => {
        try{
          if(result.hasOwnProperty('Item') &&
              result['Item'].hasOwnProperty('mergingProgress') &&
              result['Item']['mergingProgress'].hasOwnProperty('N') &&
              result['Item']['mergingProgress']['N'] !== null){
            var percentage = parseInt(result['Item']['mergingProgress']['N']);
            this.setState({
              progressMerging: percentage
            });
            if(percentage === 100){
              var result = await this.requestCSVDownloadURL({
                          userId: this.state.userId,
                          noteId: this.state.noteId
                        });
              var csvFileURL = await Storage.vault.get(JSON.parse(result.Payload).body.replace("\"", "").replace("\"", ""));
              this.setState({
                csvFileURL
              });
              console.log(this.state.csvFileURL)
              clearInterval(intervalId)
              return;
            }
          }
        }
        catch(e){
          alert("An error occured...\nConvertion started, just wait a few minutes to see it appear..." + e);
        }
      });
    }, 1500);
  }

But it says me that this is undefined.
I think this is into my then function
I tried adding .bind(this) to bind the context to my function but nothing has changed. Any ideas ?

Upvotes: 1

Views: 93

Answers (1)

jcubic
jcubic

Reputation: 66478

You have arrow functions everywhere so context is taken from function handleMerging(). If you call that function like this the this context will be undefined (if used strict mode) or window object. You will need to add bind to that function but use handleMerging.bind(this) only if caled from object (or as you said from React Component but it need to be class not function - simple component - because it will not have this context).

foo.x = function() {
   y.addEventListener('click', handleMerging.bind(this));
};

or with component:

class C extends ReactComponent {

   constructor() {
      var handleMerging = handleMerging.bind(this);

      handleMerging().then(...);
   }
}

but this need to be called from real object context so inside method, if called outside function/method it make no sens because this will be undefined even if you use bind.

Upvotes: 1

Related Questions