2

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

 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;
    });
  }
Tim Launders
  • 249
  • 1
  • 10

1 Answers1

1

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

Ali Sattarzadeh
  • 3,220
  • 1
  • 6
  • 20
  • Hi Sir , just a question, what makes my existing code wrong ? and why is that it is not allowed to do that mutation ? Thanks. – Tim Launders Nov 10 '22 at 13:48
  • Hi, I think this is because you cannot change value of state directly and prop.emails is value of state so you cannot use '=' to change its value what I did in second solution was just returning new value for emails and setRegionalList will set it per se if its not clear I can explain more – Ali Sattarzadeh Nov 10 '22 at 13:52