I am trying to iterate over the selected files in input, i got a weird bug that happens when i switch the below statement
Object.keys(event.target.files).forEach(key => {
const currentFile = event.target.files[key]
}
to
for (let key in event.target.files) {
const currentFile = event.target.files[key]
}
I don't understand whats the difference between these two statements, the first one works but the second one doesn't (results in weird bug where an object inside the loop becomes null.
Here is the full code :
onChange= (event) => {
const selectedFilesObject = event.target.files
let selectedFilesCount = Object.keys(selectedFilesObject).length
if (selectedFilesCount > 0) {
this.setState({ loading: true })
this.props.onLockdownChange(true)
let readFilesResult = {}
for (let key in selectedFilesObject) {
const currentFile = selectedFilesObject[key]
readFileAsByteArray(currentFile)
.then(response => {
readFilesResult[key] = {
bytes: response,
name: currentFile.name,
type: currentFile.type,
}
})
.catch(() => {
readFilesResult[key] = null
})
.finally(() => {
selectedFilesCount = selectedFilesCount - 1
if (selectedFilesCount === 0) {
this.onReadingFilesFinished(readFilesResult)
}
})
}
}
}
export const readFileAsByteArray = (file) => {
return new Promise((resolve, reject) => {
var reader = new FileReader();
var fileByteArray = [];
reader.readAsArrayBuffer(file);
reader.onloadend = (evt) => {
if (evt.target.readyState == FileReader.DONE) {
var arrayBuffer = evt.target.result,
array = new Uint8Array(arrayBuffer);
for (var i = 0; i < array.length; i++) {
fileByteArray.push(array[i]);
}
resolve(fileByteArray)
}
}
reader.onerror = error => {
reject()
};
})
}
I just need to understand why using for loop causes readFilesResult
to have a null length! but using object.keys().forEach
doesn't!