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 how to clone props

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.

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

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.

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