I’m learning
I have problem with this function in my component:
...
export default function Main(props) {
...
...
...
const deleteMessage = (index) => {
let test = props.data.contacts;
// let test2 = { ...props.data.contacts}; Also tried with this
test[currentContact].messages.splice(index, 1);
// props.setData({ ...props.data, test }) this is commented and should't be executed
}
return (...<JSX Elements>...)
}
When I run <li onCLick={() => deleteMessage(index)}> Delete this message </li> the change is performed on the parent component’s status.
Although props.setData () is commented out in this sample code, props.data is still affected by this function’s changes.
How can I clone props.data in a new object and work only on this, without chaging props.data?
>Solution :
When updating the state make sure that every part of the nested structure until you reach the actual thing that you want to update gets cloned.
test[currentContact].messages.splice(index, 1);
This is bad because splice modifies the messages array.
Infact test[currentContact].messages itself is bad because test[currentContact] is being mutated.
// let test2 = { ...props.data.contacts}; Also tried with this
Object and Array spread syntaxes can be used to clone and prevent mutation, but here too make sure that props.data gets cloned first and then contacts.