In the last lecture we started removing persons,
we did this by getting access to all the persons in the state, removing the one element we wanted to
remove by using the index of the person and updating the state.
The flaw of this approach is that in javascript, objects and arrays are reference types,
so when I get persons from my state as I do here I actually get a pointer to the original person's object
managed by react, to the original state
I should say. If I then splice it here, I already mutate this original data and whilst it does work without
throwing an error, this is not really how you should do it,
this can lead to unpredictable apps and is definitely a bad practice.
A good practice is to create a copy of your persons array before manipulating it and 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 here.
And you can now safely edit this new one and then update to react state with your new array.
An alternative to this approach would be to use it a ES6 feature, the spread operator. You can simply
set persons equal to a new array and this new array can now use the spread operator which are three dots
might look strange but this is a javascript
operator where are you now reach out to state persons.
What this does is it spreads out the elements in this array into a list of elements which simply then
gets added to this array, so that now we have an array, a new array, with the objects from the old array
but not the old array itself.
So this is basically an equivalent to the slice approach,
use whichever one you prefer,
this is the more modern one and you will see this spread operator more often throughout the course.
With that we get the same behavior as before and we didn't fix the error messages with that,
it still works as before but I can tell you it is the better approach of updating state.
You should always update state in an immutable fashion, so without mutating the original state first.
Create a copy, change that and then update the state with said state.
Still there are things we can and should improve about our list though.