3

I am trying to iterate all files from the file input and are following a sample. I get values from the upload control but I cannot iterate it. Is it because it is async, or there is some protection in the browser? I can see the array in the console.

const { useState } = React;

function App() {
  const [files, setFiles] = useState([]);

  const selectedFilesChanged = e => {
    var filesArr = Array.prototype.slice.call(e.target.files);
    console.log(filesArr);
    setFiles(files);
    console.log(filesArr);
    // console.log(e.target.files);
    //alert(e);
  };

  return (
    <div className="App">
      <input type="file" multiple onChange={selectedFilesChanged} />
      <div>{files.length}</div>
      <div>
        {files.map((file, index) => (
          <div key={index}>dfsdf</div>
        ))}
      </div>
    </div>
  );
}

ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Thomas Segato
  • 4,567
  • 11
  • 55
  • 104

1 Answers1

2

files is an empty array.

const [files, setFiles] = useState([]);

const selectedFilesChanged = e => {
    var filesArr = Array.prototype.slice.call(e.target.files);
    setFiles(files);
};

Use filesArr instead.

setFiles(filesArr);
kind user
  • 40,029
  • 7
  • 67
  • 77
  • 1
    OMG! Sorry to waste your time, I have just found so many samples did not get it. Thank a lot I have been working to much here. – Thomas Segato May 02 '20 at 11:59