Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

84
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda