0

I have an object as array which is store in variable

0 : {option: "E", primary: "primary", color: "#4CAF50"}
1 : {option: "B", primary: "primary", color: "#4CAF50"}
2 : {option: "", color: "", primary: ""}
3 : {option: "", color: "", primary: ""}
4 : {option: "", color: "", primary: ""}
5 : {option: "", color: "", primary: ""}

My question how can I update specific key object without change at all this is my code

handleChange = (index, option) => {

    let navNumber = this.state.navNumber
    navNumber[index] = {
      option:option,
      primary:'primary',
      color:'#4CAF50'
    }

    this.setState({navNumber})

  };

  changeRagu = (index) => { 

    let navNumber = this.state.navNumber    
    navNumber[index] = navNumber[index].color = '#FF9800' 
    this.setState({navNumber})

  }

All I want is to update only color by specific index without make all color still empty become same

2
  • 2
    You have an array of objects, lets say your array is called test, why can't you do: test[0]['color'] = "#ff0000"; Commented Nov 7, 2017 at 8:48
  • @SPlatten i don't get it what do you mean, please elaborate more sir ? Commented Nov 7, 2017 at 8:52

1 Answer 1

3

This:

let navNumber = this.state.navNumber

is bad because you are copying the reference to the navNumber variable, rather than creating a copy of it. As a consequence, any changes you do to navNumber is basically a change to this.state.navNumber. This means that you are mutating the state directly!

Instead try this:

changeRagu = (index) => { 
  let navNumber = this.state.navNumber.slice();  //make a copy of navNumber    
  let obj = Object.assign({}, navNumber[index]);  //now copy the object at index
  obj.color = '#FF9800'
  navNumber[index] = obj
  this.setState({navNumber});
}
Sign up to request clarification or add additional context in comments.

5 Comments

An array of objects is, technically, an array of object references. You've successfully copied the array of references, but the references are still the same.
@Cerbrus, that should do it :)
Thanks Chris, it give me pain googling more than one hours, my question why i should copy the variable state instead using existing variable,
@FreddySidauruk I explain that above. If you do let navNumber = this.state.navNumber and then do navNumber = 123 that means that automatically this also happens this.state.navNumber = 123. It is anti-pattern to mutate this.state directly without using this.setState().

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.