Automatic State mutation in ReactJS - Issue

Viewed 33

I am using State in React and I have placed an onChange listener on an input component which calls nameChangeHandler, and I am running into a strange mutation issue.

Here is my state object:

state = {
    persons: [
      { id: '363724', name: 'Person1', age: 28, job: 'React Developer' },
      { id: '724324', name: 'Person2', age: 49, job: 'General Manager' },
      { id: '753424', name: 'Person3', age: 25, job: 'ITSM Consultant' }
    ]
};

And then the below code this.state.person logs updated state with an extra character(which I type in), even though I am not using setState anywhere and neither I am mutating the state directly.

nameChangeHandler = (event, id) => {
    const personIndex = this.state.persons.findIndex(p => p.id === id);
    const newPersons = [...this.state.persons];
    
    newPersons[personIndex].name = event.target.value;
  
    console.log(newPersons);
    console.log(this.state.persons);
    //this.setState({});
};

Here is a screenshot of dev console.

automatic mutation of state

Can someone help?

1 Answers

Es6 spread syntax does shallow copy not deep copy.So when you are trying to create new nested objects from existing one you have to use deep copy methods.

For deep-copying of nested objects you can use JSON.parse(JSON.stringify(object))

Here you have an array of objects so what you can do is:

let newPersons = this.state.persons.map(person => {return {...person}})
Related