Reputation: 4253
I have image state:
class imageUpload extends Component {
constructor(props) {
super(props);
this.state = {
image: null
}
in my return I have this on change:
<input type="file" id="select" onChange={this.handleChange}/>
and this code to get the image...
handleChange = e => {
if (e.target.files[0]) {
const image = e.target.files[0];
this.setState(() => ({image}));
{this.upload()}
}
}
handleUpload = () => {
const {image} = this.state;
}
upload = () => {
ImageTools.resize(this.state.image, { //TypeError: Cannot read property 'resize' of undefined
width: 320,
height: 240
}, function(blob, didItResize) {
document.getElementById('preview').src = window.URL.createObjectURL(blob);
const uploadTask = storage.ref(`images/${this.state.image.name}`).put(blob);
uploadTask.on('state_changed',
(snapshot) => {
why this.state.image is giving me TypeError: Cannot read property 'resize' of undefined
when I select an image?
how to solve?
Upvotes: 0
Views: 766
Reputation: 53874
Firstly note that you component name should be uppercased ImageUpload
or React will think it's a DOM element.
Because this.setState
is async, on calling this.upload
straight after setState
will use the current state value which is image: null
.
If you depend on state, you may want to try:
this.setState({image});
this.state.image && this.upload();
Or use the actual image
value:
// use image argument in upload
this.upload(image);
Or if you trying to use upload
after updating the state, you may want to try the callback
argument of setState
:
// setState(updater, [callback])
this.setState({ image }, this.upload(image));
Upvotes: 1