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;
});
}
CodePudding user response:
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