0

I have a state of an array like this:

constructor(props){
   super(props)
   this.state={
      test_steps: []
   }
}

and it holds the following properties:

test_steps: [
    {
        description: "Test desc"
        expected_results: "Test exp. results"
        other_info: "test other info"
        status: true
        step_number: "1"
        _id: {$oid: "1234565894"}
    }
]

If I wanted to update only **other_info** property on this state, how will I achieve that?

SamWhite
  • 89
  • 3
  • 11
  • 2
    Possible duplicate of [React: How do I update state.item\[1\] on setState? (with JSFiddle)](https://stackoverflow.com/questions/29537299/react-how-do-i-update-state-item1-on-setstate-with-jsfiddle) – azium Aug 16 '18 at 22:42

2 Answers2

1

Since there is one element in your array you can use spread syntax, then change the related property.

this.setState(prevState => ({
      test_steps: [
        {
          ...prevState.test_steps[0],
          other_info: "foo"
        }
      ]
}));
devserkan
  • 16,870
  • 4
  • 31
  • 47
1

You first need to get the your state and store it in variable. Then you loop the value and modify it. After that just set the state.

let test_steps = this.state.test_steps;
    test_steps.map((test)=>{
    test.other_info = "YOUR_UPDATED_INFO";
    return test;
    });

this.setState({test_steps});
Vynart
  • 95
  • 4