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

125
Vistas
ReactJS not rendering correct items after splice

So I am attempting to delete an item from an array in React, but after deleting (using splice) item 2 from [1, 2, 3, 4] it re-renders the array to be [1, 2, 3] (at least visually) but when I render one more time (by closing the array and opening it) it renders properly as [1, 3, 4]. Not sure why it's doing this and I think it has to do with splice() but nothing else seems to be working. I tried slice() as well but that didnt work either. Here is the code for my delete function:

const deleteFile = (i) => {
        console.log(files);
        const newFiles = [...files];
        console.log('before delete:', newFiles); //prints [1, 2, 3, 4]
        newFiles.splice(i, 1);
        console.log('after delete:', newFiles); //prints [1, 3, 4] but shows visually as [1, 2, 3]
        setFiles(newFiles);
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This may be one potential way to achieve the desired objective (ie, remove the element at index i in an array named files:

const [files, setFiles] = useState([]);
const deleteFile = i => setFiles(prev => prev.filter((f, idx) => idx !== i));

NOTE: Please add index-check (i should be >= 0 and < files.length) if needed.

Explanation

  • setFiles may be used with a callback (click here for more info)
  • prev is the existing array files
  • use .filter with idx to filter out the element at index i

Code Snippet

const arr = [1, 2, 3, 4];

const deleteItemAt = i => arr.filter((el, idx) => idx !== i);

console.log(deleteItemAt(1));
console.log(deleteItemAt(0));
console.log(deleteItemAt(3));

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