0

I'm getting the error when using this function:

 private _addFile = (event) => {
    //let resultFile = document.getElementById('file');
    let resultFile = event.target.files;
    console.log(resultFile);
    let fileInfos = [];
    for (var i = 0; i < resultFile.length; i++) {
      var fileName = resultFile[i].name;
      console.log(fileName + 'fileName');
      var file = resultFile[i];
      var reader = new FileReader();
      reader.onload = ((file) => {
         return (e) => {
              //Push the converted file into array
               fileInfos.push({
                  "name": file.name,
                  "content": e.target.result
                  });
                };
         })(file);
      reader.readAsArrayBuffer(file);
    }
    this.setState({
      fileInfos,
      fileArray: resultFile,  
    }, () => {
        console.log(this.state.fileArray);
    });
    
  }

and this JSX:

             {this.state.fileArray ? this.state.fileArray.map((item, i) => <li key={i}>{item}</li>) : null }

I'm still a learner to ReactJS so explanations are always helpful. I've read a few similar posts, and have tried to follow but they also cause the same error.

Randomize
  • 8,651
  • 18
  • 78
  • 133
NightTom
  • 418
  • 15
  • 37
  • Does this answer your question? [How to map through an array of input files?](https://stackoverflow.com/questions/44511925/how-to-map-through-an-array-of-input-files) – moonwave99 Aug 18 '20 at 13:04
  • Is it describing how the files are converted and pushed into the array? It's not helping unfortunately. – NightTom Aug 18 '20 at 13:24
  • 1
    It tells you why `event.target.files` does not have the `map` method (it is a FileList), so you have to convert to an array first: `let resultFile = [...event.target.files]`. – moonwave99 Aug 18 '20 at 13:29
  • I've used let resultFileArr = [...event.target.files]; and then tried to log that, getting Object doesn't support property or method 'slice' – NightTom Aug 18 '20 at 13:44

2 Answers2

1

Try use:

{
                    Object.keys(this.state.resultFile).map(key => 
                     <li value={key}>{this.state.resultFile[key].name}</li>
                )
}

Test result: enter image description here

Amos
  • 2,030
  • 1
  • 5
  • 9
0

I used:

 // @ts-ignore
    const fileListToArr = Array.from(resultFile);

Which was derived from what moonwave99 gave.

The reason is, that the filelist is not an array it is considered an object and so needs converting. The only thing I wanted from it was the names of the files, so I used the above. I also had to force ignore typeScript because it didn't like .from

NightTom
  • 418
  • 15
  • 37