Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
Iterating many files and reading them with FileReader but is not workin

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);
    }
  }
}/>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]
          });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!