nevoni3008
nevoni3008

Reputation: 447

Cannot assign to read only property of object '#<Object>'

I'm trying to create a duplicate array so I can edit the values and set it back also, here is what I got:

const handleInput: any = (index: any, property: any, value: any) => {
  const newCertificates = [...props.resume.certifications];
  newCertificates[index][property] = value;
  props.setResume({ ...props.resume, certifications: newCertificates })
}

But I get this error:

Certificates.tsx:18 Uncaught TypeError: Cannot assign to read only property 'certificationName' of object '#<Object>'

Upvotes: 2

Views: 6625

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50639

You're trying to modify your state directly, as the objects within newCertificates are still the same objects that they referred to in your original state. Using [...] only creates a shallow copy of your array, so the objects within are not cloned (see here for more details). On React, you shouldn't modify state directly as that can lead to issues with re-rendering, and that is what TS is trying to tell you with the error.

Rather than modifying these objects, use .map() on props.resume.certifications and then return a new object once you find the object that you need to modify and return a new object with the updated value:

props.setResume(resume => ({
  ...resume,
  certifications: resume.certifications.map((obj, i) => 
    i === index ? {...obj, [property]: value} : obj
  )
}));

This way, you're only reading and never writing to your state value.

Upvotes: 2

Related Questions