Reputation: 73
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)
//}
}
Upvotes: 3
Views: 1163
Reputation: 39270
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);
}
}
};
};
};
Upvotes: 1