javascriptreactjstransloadit

'this' is not a function in code splitting


I don't know how to deal with the problem of 'this' in my code. Everything was working fine until I used code splitting.

I am trying to import component after clicking on button. So I have removed componentWillMount.

Before code splitting:

import React, {PureComponent} from 'react';
import Uppy from 'uppy/lib/core';

 class Shopper extends PureComponent {
    constructor (props) {
    super(props); }

   componentWillMount () {
    this.uppy2 = new Uppy({ 
      autoProceed: false,
        onBeforeUpload: (files) => {
          const updatedFiles = Object.assign({}, files)
          Object.keys(updatedFiles).forEach(fileId => {
           let origName = updatedFiles[fileId].name;
           let metaName =  updatedFiles[fileId].meta.name;
            /* some code */

            if (fileDir) {
              this.uppy2.setFileMeta(uploadId, { name: `${addBeforeName}-${metaName}.${updatedFiles[fileId].extension}` })
            /* some more codes */
          } else {
              /* some more code */
          }
        })
        return updatedFiles 
      }
       })

After code splitting:

import React, {PureComponent} from 'react';

 class Shopper extends PureComponent {
    constructor (props) {
    super(props); 

   this.uploadModal = this.uploadModal.bind(this);
}

uploadModal () {
    this.uppy2 = import('uppy/lib/core')
      .then((uppydata) => new uppydata({
        autoProceed: false,
        onBeforeUpload: (files) => {
          const updatedFiles = Object.assign({}, files)
          Object.keys(updatedFiles).forEach(fileId => {
            let origName = updatedFiles[fileId].name;
            let metaName =  updatedFiles[fileId].meta.name;

            if (fileDir) {
              this.uppy2.setFileMeta(uploadId, { name: `${addBeforeName}-${metaName}.${updatedFiles[fileId].extension}` })

            /* Here this.uppy2.setFileMeta is giving error */

          } else {
             / * some more code */
          } 
        })
        return updatedFiles 
      }
       })
      )
      .then(useTus => { 
    /* some more codes */
    })

After code splitting I am getting this error:

Uncaught TypeError: _this2.uppy2.setFileMeta is not a function


Solution

  • You are assigning uppy2 to a promise, not to the class instance:

    import('uppy/lib/core').then((uppydata) => {
      this.uppy2 = new uppydata({
        autoProceed: false,
        onBeforeUpload: (files) => {
          const updatedFiles = Object.assign({}, files)
          Object.keys(updatedFiles).forEach(fileId => {
            let origName = updatedFiles[fileId].name;
            let metaName =  updatedFiles[fileId].meta.name;
    
            if (fileDir) {
              this.uppy2.setFileMeta(uploadId, { 
                name: `${addBeforeName}-${metaName}.${updatedFiles[fileId].extension}` 
              })
    // ...