In the lest lesson we started removing persons. we did this by getting access to all the persons in the state, removing the one element who wanted to remove by using the index of the person and updating the state. The flaw of that approach is that javascript objects and arrays are reference types. So when I get persons from our state as we did in the last lesson, we act a pointer to the original person’s object managed by React. Then if we splice the already mutate the original data and while it does work without throwing an error, this is not really how you should do it. this can lead to unpredictable apps and is a bad approach.
A good practice is to create a copy of your persistence array before manipulating it.
A simple way of doing this is by calling the slice() method. slice without arguments simply copies the full array and returns a new one which is then stored to its assigne. example: in App.js
slice()
... deletePersonHandler = personIndex => { const persons = this.state.persons.slice(); // Creates a new copy of array persons.splice(personIndex, 1); this.setState({ persons: persons }); }; ...
And then you can safely edit the new array and then update do react state with your new array.
An Alternative to this approach would be to use a ES6 feature i.e. the spread operator you can simply set persons equals to new arrays example: in App.js
... deletePersonHandler = personIndex => { // const persons = this.state.persons.slice(); const persons = [...this.state.persons]; // Creates a new copy of array persons.splice(personIndex, 1); this.setState({ persons: persons }); }; ...
new array can now use spread operator which are three dots ... , might looks strange but it is a javascript operator. what it does is, it spread out the elements of array into a list of elements which simply then gets added to the const persons array. So now we have an array a new array with the objects from the old array but not the old array itself. so that is equivalent to the slice approach use whichever one you prefer. but the spread operator (...) is a more modern one and you will see this spread operator more throughout this course. With this we get the same behavior as before and, we didn’t fix the error message with that.
...
const persons
slice
you should always update state in an immutable fashion so without mutating the original state first, reate a copy change that and then update the state with setState().
setState()