I can add or delete when I haven’t saved the data to database. Once it’s saved and I want to update them either by deleting them or adding a new value. It gives this error "can’t define array index property past the end of an array with non-writable length". How can I solve this issue?
const handleDeleteDepartment = (companyIndex, departmentIndex) => {
if (departmentIndex !== 0) {
const newCompanies = [...companies];
newCompanies[companyIndex].children.splice(departmentIndex, 1);
setCompanies(newCompanies);
}
};
2
Answers
you need more checks here before executing this line:
newCompanies[companyIndex]
exists:departmentIndex
is not higher than thenewCompanies[companyIndex].children
length:newCompanies[companyIndex].children
is an array:and this should not fail:
If you are simply just trying to remove an element from an array at a specific index then I’d suggest (A) using a functional state update to ensure you are updating from the correct previous state value and (B) use
Array.prototype.filter
to create a new array reference. UsingArray.prototype.splice
mutates an array in-place, and state mutations are a huge no-no in React.The following applies the immutable update pattern, e.g. all state, and nested state, that is being updated is shallow copied prior to being updated. This ensures all updated state are new references in memory and React can correctly reconcile what needs to be rerendered for the next render cycle.
Example: