I want to have a upload mechanism which uploads pictures and turns them into base64 strings and then save them to a state. After that, I want to map in in a component. But it turns out, that Array.map() returns a empty array in this situation. Does array.map has a limitation?
class TestFileInput extends React.Component {
constructor(props){
super(props);
this.fileToBase64 = this.fileToBase64.bind(this);
this.state = {
examplePictures: undefined
}
}
fileToBase64(files){
let array = [];
for(let i = 0; i < files.length; i++){
let reader = new FileReader();
let file = files[i];
reader.onload = function(event) {
// Push to array
array.push(event.target.result)
};
reader.readAsDataURL(file);
}
//return array
return array;
}
render() {
console.log(this.state.examplePictures);
return (
<div>
<input type="file" multiple onChange={(e) => {
this.setState({
examplePictures: this.fileToBase64(e.target.files)
})
}}/>
{this.state.examplePictures !== undefined ? (
<div>
{this.state.examplePictures.map(pic => (
<img src={pic} alt=""/>
))}
</div>
):""}
</div>
);
}
}
So basically, when you upload pictures. The fileToBase64 is getting called, returns an array (which works) with base64 strings. They get saved to the state (which works too). Only the mapping returns a empty array.
Here is a fiddle https://jsfiddle.net/op69hbxm/3/
arraywill be[], because you haven't chained the onLoad event.pushwill happen later after returningarrayreader.onloadin there.{console.log(this.state.examplePictures);this.state.examplePictures.map()}.pushworks, but only after returning a empty array.