So I'm trying to iterate multiple files and read them with FileReader and add to React State, so I have this code that It works when I upload one file, but on iteration it doesn't work even that it should, I get in the state only the first file but no all of them.
<input
className={styles.hidden_input}
type='file'
multiple='multiple'
accept='image/*'
onChange = {
(event) => {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const image = files[i];
const reader = new FileReader();
const randomizer = `${Date.now() * Math.random()}`;
const images = [...data.images];
reader.addEventListener(
'load',
function() {
const img = {
id: randomizer,
name: image.name,
stream: reader.result,
type: image.type,
};
setData({
...data,
images: [...images, img]
});
},
false
);
if (image) reader.readAsDataURL(image);
}
}
}/>
Using this line:
const images = [...data.images];
captures the current value of data.images which is probably almost always [].
Because this is now always [] for each image being read,
when you spread it back into the state, you're doing this:
[...[], img]
Which is overriding the images that were read.
To fix this, just spread the current value directly without capturing it:
setData({
...data,
images: [...data.images, img]
});