I made a class compontent for upload images everything are good and now I want to upload it to server via api but there is one problem, when you select first image, it look like not working, it must call handleUpload function, but it seems this.state.images not updated yet, when you select second image, now it call upload function. what I have done wrong? how to make this.state.images update for uploading.
class Hello extends React.Component {
constructor() {
super();
this.state = {
image: [], //store real image files
images: '', // base64
urlImage: [] // blob
};
}
handleImage = (e) => {
let image = e.target.files;
let array = [];
let urlArray = [];
let result = [...this.state.image, ...image];
this.setState({
image: result
})
result.map(function(img, i) {
let fileReader = new FileReader();
let blob = URL.createObjectURL(img);
urlArray.push(blob);
fileReader.readAsDataURL(img);
fileReader.onload = () => {
array.push(fileReader.result);
}
})
this.setState({
images: array,
urlImage: urlArray
})
this.handleUpload();
}
handleUpload = ()=> {
this.state.images && this.state.images.map(function (v, i){
let data = {image: v};
console.log(data); // this not working for first time
// upload to api
})
}
render() {
let real_this = this.state;
let Images = this.state.urlImage;
let ImageList = Images.map(function(Img, Row){
return (
<div key={Row}>
<img alt="" className="img-thumbnail m-2" width="100" height="100" src={Img}/>
</div>
)
})
return <ul>
<li>
<input type="file" multiple={true} onChange={this.handleImage}/>
</li>
<li>
{ImageList && ImageList}
</li>
</ul>;
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="container"></div>