I want to try deleting the technologies data according to the index using the handleDeleteTechnology function but when I try to delete it and it works if I see the data in the data, but in the UI what is deleted is always the last index even though I want to delete the first index.
const handleDeleteTechnology = (index) => {
const updatedTechnologies = [...technologies];
updatedTechnologies.splice(index, 1);
setTechnologies(updatedTechnologies);
const updatedDetailTechData = [...detailTechData];
updatedDetailTechData.splice(index, 1);
setDetailTechData(updatedDetailTechData);
return setFilesTech(prevFilesTech => {
const updatedFilesTech = [...prevFilesTech];
updatedFilesTech.splice(index, 1);
return updatedFilesTech;
});
};
{technologies.map((tech, index) => (
<div className='flex' key={index} index={index}>
<div className='relative'>
<FaCircleMinus size={25} className='absolute -top-2 -left-2 text-red-600' onClick={() => handleDeleteTechnology(index)} />
</div>
<UploadTechnology
index={index}
technology={tech}
onImageChange={(index, imageUrl) => handleImageChange(index, imageUrl)}
/>
</div>
))}
I’ve tried searching on Google or chatgpt but still haven’t found this problem
4
Answers
React detects the changes by comparing the keys. It is not recommended to have index as key, especially when the array is involved in deletion operation. Can you please try setting the tech itself as key instead of index. like this.
Seems the issue lies in the use of
index
from map function.To use this, it needs to re-render the components whenever an item is deleted.
I am not sure this logic has been implemented since I cannot see the whole code.
It would be good if you can provide full code in this component.
BTW, what is the best approach is to use the
id
in the technologies object array itself if it has.It seems you’re parsing ‘index’ to an unknown prop for the div element
<div ... index={index} />
You only have to parse the ‘index’ to the ‘key’ property of the div element so React can track each object of the array.
However, for the
<UploadTechnology />
component, you have a custom ‘index’ property which you’re probably using to track each object and respond to them in the component to render its children dynamically, which is fine.Here’s my suggestion:
Simple change this
Or can change and update functions