I have the following react code
constructor(props) {
super(props);
this.state = {registrations: [{firstName: "foo", lastName: "bar", activity: "Science Lab", restrictions: "a,b,c"}]}
}
addRegistration(registration) {
console.log('came inside event handler to add registration')
console.log(registration)
console.log('existing state')
console.dir(this.state.registrations)
var newState = this.state.registrations.splice() // copy
console.dir(newState)
newState.push(registration)
console.log(newState)
this.setState({registrations: newState})
}
when I run my code and the addRegistration event handler is called I see the following output
[Log] {firstName: "Foo", lastName: "Bar", activity: "Swimming", restrictions: "a,b"} (Registration.html, line 404)
[Log] existing state (Registration.html, line 405)
[Log] [Object] (1) (Registration.html, line 406)
[Log] [] (0) (Registration.html, line 408)
[Log] [Object] (1) (Registration.html, line 410)
so I get a valid registration object as input parameter. In the 3rd entry of the log we see that the existing state had an array of size 1. (which is the foo object from the constructor
next we see that the call to this.state.registrations.splice() created and empty array. and then the new registration object received as parameter is pushed into the empty created thereby creating another Array of size 1.
I don't understand why splice() created an empty array. it should have returned me a copy of the existing state and then the push should have resulted in an array size of 2.
what did I miss?
.slice()to make copy not.splice()