I'm fetching data from an API and then I save an array inside a state. While I'm trying to modify the specific field in object inside an array using input, I'm getting the following error: 'Uncaught TypeError: Cannot assign to read only property 'amount' of object '#''.
States (I'm using RTK Query):
const { data: Florists_data, refetch } = useGetFloristQuery(Number(sessionStorage.getItem('florist_id')));
const [flowersData, setFlowersData] = useState(Florists_data?.florist[0].flowers);
const [tmpFlowers, setTmpFlowers] = useState(Florists_data?.florist[0].flowers);
Update function:
const updateFieldChanged = (index: number, e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
let newArr = [...tmpFlowers!];
newArr[index].amount = Number(e.target.value); //GETTING ERROR HERE
setTmpFlowers(newArr);
}
Inputs:
{flowersData?.map((flower, index) => {
return (
<>
<div className={classes.Nested_Flower_Container} key={index}>
<div className={classes.Nested_Flower_Name}>
{flower.name}
</div>
<div className={classes.Nested_Flower_Input} style={{ marginRight: '0.2em' }}>
<TextField
id="Amount"
label="Amount"
variant="outlined"
size="small"
type="number"
onChange={(e) => {
updateFieldChanged(index, e);
}}
className={classes_2.root}
/>
</div>
</div>
</>)
})}
Spread operator normally creates a new object in memory, not just an address pointer. But when using it on an array of objects, it creates a second array like usual, but with all the objects inside being memory pointers. In short, what I believe is happening is the objects cant be changed because they're not copies. Try finding a deep clone code and testing of it works. (This is what's happening https://media.discordapp.net/attachments/335455578921107456/940745267324534825/MMAsMng1.png) which I also suspect is erroring out because you're modifying the state in an unapproved way