3

If i used setState or any other functions in image.onload callback then i got error like this is not function. And if i used local variable to handle error then condition was checked before value of local variable will be updated in image.onload.

handleProductImage = (e) => {
    let file = e.target.files[0];
    let reader = new FileReader();
    let  height, width, isError = false;
    reader.readAsDataURL(file);
    reader.onload = function (file) {
      let img = new Image();
      img.src = file.target.result;
      img.onload = function () {
        height = this.height;
        width = this.width;
        if (height && width) {
          if (height < 250 || width < 250) {
             //--Use local variable---//
             //isError = true;
            //---Use setState for handle error---//
            // this.setState({ isError: true });
            //---Call function directly---//
            this.props.setErrorMessage();
          }
          else {
            //--Use local variable---//
            //isError = false;
            //---Use setState for handle error---//
            // this.setState({ isError: false });
            //---Call function directly---//
             this.handleImageCropper(e)
          }
        }
      }
    }
    //Use local variable for function call 
    //if (isError) {
      //console.log("error");
      //this.props.setErrorMessage();
    //}
    //else {
      //this.handleImageCropper(e)
    //}
  }
0

1 Answer 1

1

You use this and sometimes assume it's the image but later assume it is the component. Try the following:

handleProductImage = (e) => {
  const me = this;
  let file = e.target.files[0];
  let reader = new FileReader();
  let height,
    width,
    isError = false;
  reader.readAsDataURL(file);
  reader.onload = function (file) {
    let img = new Image();
    img.src = file.target.result;
    img.onload = function () {
      height = this.height;//leave "this" if you mean img.height
      width = this.width;
      if (height && width) {
        if (height < 250 || width < 250) {
          me.props.setErrorMessage();
        } else {
          me.handleImageCropper(e);
        }
      }
    };
  };
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.