Search code examples
javascriptreactjsreduxfluxreactjs-flux

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?


Solution

  • 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