Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: "TypeError: Object(...)(...) is undefined"

In the code below:

handleImageChange = (newFile, crop) => {
    var string = RandomString.generate(20);

    newImage(string, newFile, this.state.type, 0)
    .then((result) => {
      if(result) {
        this.toggleModal();
      }
    });
}

saveCropped() {
  var values = this.cropper.values();
  var crop = this.cropper.crop();
  var newFile = convertBase64ToFile(crop);

  setTimeout(function() {
    this.handleImageChange(newFile, crop);
  }.bind(this), 5000);
}

The function called is saveCropped() which then calls the handleImageChange function.

What this function does (newImage) is send an Axios request to my server, but when I run it I get the following error: "TypeError: Object(...)(...) is undefined"

The thing is, even tho I'm getting this error, the code executes in the background with no problem i.e. the request is sent to my server and I get a response in the console.

The error points to line 5 (newImage(...)).

The newImage function works because this is not the only place where its called and the function only returns a boolean; even so here it is:

function newImage(image_ID, image, imgType, type) {
    var url = ...;

    const header = {
      headers: {
        'Content-Type': imgType
      }
    };

    axios.post(url, image, header)
    .then(function (response) {
      if(response.status === 200) {
        if(type !== '1')
          sessionStorage.setItem('avatar', image_ID);
        console.log("Image uploaded!");
        return true;
      }
      else
        return false;
    })
    .catch(function (error) {
      console.log(`Image could not be uploaded due to:\n${error}`);
      return false;
    });
}

What am I doing wrong here?

like image 690
Asfourhundred Avatar asked May 30 '18 14:05

Asfourhundred


1 Answers

You are trying to call then() on the return value of newImage() … but that function doesn't have a return statement.

Presumably, you want to return the promise returned by calling axios.post:

return axios.post(url, image, header).
    etc etc
like image 199
Quentin Avatar answered Nov 08 '22 02:11

Quentin