2

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?

2
  • 4
    use .slice() to make copy not .splice() Commented Mar 17, 2018 at 19:39
  • ah.... that was simple thanks! Commented Mar 17, 2018 at 19:40

1 Answer 1

4

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.