Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

83
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda