React state is updating without calling setState

Viewed 975

My state is changed even i have created new variable and without calling setState.

This is my code

changeName = (event, id) => {
    const persons = [...this.state.persons]; // Create a copy of array using spread operator
    const person = persons.find(cur => cur.id === id);
    person.name = event.target.value;

    console.log(persons);
    console.log(this.state.persons);
}

render() {
    let allPersonsArr = this.state.persons.map(cur => {
        return <Person name={cur.name} age={cur.age} job={cur.job} key={cur.id} change={(event) => this.changeName(event, cur.id)}/>;
    });

    return(
        <div>
            {allPersonsArr}
        </div>
    );
}

the state.persons has changed upon checking into the console after using person.name = event.target.value even though i'm pointing to the new array persons

2 Answers

Spread syntax just creates a one level deep copy of the array and not a deep copy and since you have objects inside your arrays, setting person.name changes the original object

changeName = (event, id) => {
    const persons = this.state.persons(person => {
        if (person.id === id) {
            return {...person, name: event.target.value}
        }
        return persons;
    })
    this.setState({ persons })
}

Your code actually not change the main object of your state. It just edits a (not deep) copy of the state.

To have an original update you should call setState. Also to be sure that your updates do not effect on a copy, you can use React Immutability Helpers.

Related