Reputation: 31546
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?
Upvotes: 2
Views: 1071
Reputation: 281874
splice
return you the array of deleted elements, whereas slice()
method returns a shallow copy of a portion of an array into a new array object selected from begin
to end
(end not included). you can create a copy of array by using spread operator syntax or using slice like
var newState = this.state.registrations.slice()
or
var newState = [...this.state.registrations]
Upvotes: 4