0

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);
}
  • A minimum reproducible example will be great, I don't understand what you mean by "shows visually". Is not clear what is your original input array, your input to the deleteFile function and the desired output – Ricardo Sanchez Feb 03 '22 at 14:46

1 Answers1

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));
jsN00b
  • 3,584
  • 2
  • 8
  • 21