Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react issue – Cannot assign to read only property '0' of object '[object Array]' —

What causes the ff issue ? Cannot assign to read only property ‘0’ of object ‘[object Array]’ ?

Any idea would be appreacited. Thanks.

#ts code snippet

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 const [RegionalList, setRegionalList] = useState<IRegionalList[]>(RegionalListData);


 const setEmailValue = (event: any, regionalId: number, index: number) => {
    setRegionalList((prevState: IRegionalList[]) => {
      const newState = prevState.map((prop: IRegionalList) => {
        if (prop.id === regionalId) {
          prop.emails[index] = { emailAddress: event.target.value, id: null };
          return { ...prop };
        }
        return prop;
      });
      return newState;
    });
  }

>Solution :

here is the way that I suggest :

 const [RegionalList, setRegionalList] = useState<IRegionalList[]>(RegionalListData);


 const setEmailValue = (event: any, regionalId: number, index: number) => {
    setRegionalList((prevState: IRegionalList[]) => {
      const newState = prevState.map((prop: IRegionalList) => {
        if (prop.id === regionalId) {
         return { ...prop,emails:[...prop.emails.filter( (_,i)=>i !== index ),{ emailAddress: event.target.value, id: null }] } 
        }
        return prop;
      });
      return newState;
    });
  }

and if you care about order of your list you can do this :

    const setEmailValue = (event: any, regionalId: number, index: number) => {
    setRegionalList((prevState: IRegionalList[]) => {
      const newState = prevState.map((prop: IRegionalList) => {
        if (prop.id === regionalId) {
         let emails = prop.emails;
         emails[index] = { emailAddress: event.target.value, id: null };
          return { ...prop,emails }
        }
        return prop;
      });
      return newState;
    });
  }

please let me know if it fixed your problem

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading