George Welder
George Welder

Reputation: 4055

Am I modifying my Redux state here?

I am not sure whether this is modifying my redux state:

var tempArray = this.props.currentView.someArray;
    tempArray.push(this.state.inputField);

Is the first line copying the contents, or is this creating an actual reference to the props object?

Upvotes: 2

Views: 56

Answers (1)

powerc9000
powerc9000

Reputation: 2103

var tempArray = this.props.currentView.someArray;

will make tempArray reference the array.

tempArray.push() modifies the reference.

So yes, it will modify this.props.currentView.someArray.

If you don't want to modify your state you could do.

var tempArray = this.props.currentView.someArray.slice();

Slice won't modify the original array and calling it with no arguments returns a copy of the original array.

Modifying tempArray after this will have no effect on this.props.currentView.someArray

Upvotes: 4

Related Questions