skip to Main Content

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


  1. you need more checks here before executing this line:

    newCompanies[companyIndex].children.splice(departmentIndex, 1);
    
    1. you want to be sure that newCompanies[companyIndex] exists:
    if(newCompanies[companyIndex])
    
    1. you want to be sure the departmentIndex is not higher than the newCompanies[companyIndex].children length:
    departmentIndex < newCompanies[companyIndex]?.children.length
    
    1. you want to be sure that newCompanies[companyIndex].children is an array:
    Array.isArray(newCompanies[companyIndex].children)
    

    and this should not fail:

    const handleDeleteDepartment = (companyIndex, departmentIndex) => {
      const newCompanies = [...companies];
      if (departmentIndex !== 0) {
        if (
          newCompanies[companyIndex] &&
          Array.isArray(newCompanies[companyIndex]?.children) &&
          departmentIndex < newCompanies[companyIndex]?.children?.length
        ) {
          newCompanies[companyIndex].children.splice(departmentIndex, 1);
          setCompanies(newCompanies);
        }
      }
    };
    
    Login or Signup to reply.
  2. 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. Using Array.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:

    const handleDeleteDepartment = (companyIndex, departmentIndex) => {
      if (companyIndex >= 0 && departmentIndex >= 0) {
        setCompanies(companies => companies.map((company, compIndex) => 
          compIndex === companyIndex
            ? {
              ...company,
              children: company.children.filter(
                (_, deptIndex) => deptIndex !== departmentIndex
              ),
            }
            : company
        ));
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search