'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);
}
Solution 1:[1]
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 (
ishould be>= 0and< files.length) if needed.
Explanation
setFilesmay be used with a callback (click here for more info)previs the existing arrayfiles- use
.filterwithidxto filter out the element at indexi
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));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jsN00b |
