0

after setup a simple image upload i've tried to call another function from a function and the logs spits out

Unhandled Rejection (TypeError): self.sendImage is not a function

logs

here is the code

  readFile(files) {
        var self = this;
    if (files && files[0]) {
      let formPayLoad = new FormData();
      formPayLoad.append("attachment_image", files[0]);
      self.sendImage(formPayLoad);
    }

  }

  sendImage(formPayLoad) {
    let auth_token = window.localStorage.getItem("auth_token");
    fetch("/posts", {
      headers: {
        Accept: "application/json",
        Access: auth_token
      },
      method: "POST",
      body: formPayLoad
    })
      .then(response => response.json())

  }

To fix it i've tried to change the variable this to self and still persist the error.

so, please, can someone clarify why this Unhandles Rejecton? is related to class Es6?

1 Answers1

-1

You may need to bind the function inside the constructor ex

this.sendImage = this.sendImage.bind(this);

or you can use ES6 and use an arrow function to eliminate the need for an arrow function

sendImage = (formPayLoad) => {
    let auth_token = window.localStorage.getItem("auth_token");
    fetch("/posts", {
      headers: {
        Accept: "application/json",
        Access: auth_token
      },
      method: "POST",
      body: formPayLoad
    })
      .then(response => response.json())

  }
Jacob Bralish
  • 261
  • 3
  • 13