Home > Blockchain >  TypeError: can't define array index property past the end of an array with non-writable length
TypeError: can't define array index property past the end of an array with non-writable length

Time:10-28

i am updating state in form by dynamically adding form fields but this error is coming up what i have tried what should happen is that more fields should be added to each subfields on click if i want

const addExperience = () => {
    let temp = Object.assign({}, form);
    temp.experience.push({
      company: "",
      position: "",
      startDate: "",
      endDate: "",
      description: "",
    });
    setForm(temp);
  }

this is the form

const [form, setForm] = useState({
    name: "adarsh raj",
    email: "[email protected]",
    phone: "83404dvsdsd",
    address: "patel chowk",
    city: "deoghar",
    education: [
      {
        school: "dav ",
        major: "intermediate",
        GPA: "8.12",
      },
    ],
    experience: [
      {
        company: "venturepact llc",
        position: "associate software developer",
        startDate: "dd-mm-yyyy",
        endDate: "dd-mm-yyyy",
        description: "description",
      },
    ],
    projects: [
      {
        projectName: "project name",
        projectDescription: "project description",
      },
    ],
    skills: [
      {
        skillName: "your skill name",
      },
    ],
  });

CodePudding user response:

code like this should work. But to test, you can try this syntax:

  const addExperience = () => {
    let temp = Object.assign({}, form);
    temp.experience = [
      ...temp.experience,
      {
        company: "",
        position: "",
        startDate: "",
        endDate: "",
        description: ""
      }
    ];
    setForm(temp);
  };

CodePudding user response:

Object.assign(target, source) just Shallow copy.

useState return value is Immutable;

Refer to the following demo

var x = new Array(10).fill(0);
Object.freeze(x);
x.push(11) // same error 

You can solve this problem by deep copying or reassigning the experience of the first layer.

Only the first layer can be assigned because a shallow copy is used. It cannot be resolved if the problem attribute appears at the second level. Therefore, this method is not recommended and deep copy is recommended.

let temp = JSON.parse(JSON.stringify(form));
let temp = lodash.cloneDeep(form);// need install lodash
  • Related