0

My state values are as follows:

constructor(props) {
    super(props);

    this.state = {
      list: [
        { id: '1', age: 42 },
        { id: '2', age: 33 },
        { id: '3', age: 68 },
      ],
    };
}

And my handle function is

handle() {
    this.setState(prevState => ({
        list: {
            ...prevState.list,
            [prevState.list[1]]: {
                ...prevState.list[1],
                age: 40
            }
        }
    }))
}

What I want here is to change the age of second row from 33 to 40, but my code is wrong. Can anyone suggest a correct way?

Required answer:

list: [
    { id: '1', age: 42 },
    { id: '2', age: 40 },
    { id: '3', age: 68 },
  ],
Hareesh
  • 1,507
  • 3
  • 21
  • 43
  • 1
    Your new state doesn't have the same *shape* as the old one, you're changing `this.state.list` from an array to an object. Try `{ list: prevState.list.map(...) }`. – jonrsharpe Jul 29 '19 at 09:15
  • You would need to check which row you want to change and pass that value to the handleFunction. A simple approach could be: ``list.map(each=>{ each.id==2?each.age=40:null })`` – ProblemsEverywhere Jul 29 '19 at 09:19

2 Answers2

1

The simple and efficient of doing this can be changing the array first by saving it into another variable. Then use that variable to set the state directly. You can do it like this:

handle(){
  let lists = [...this.state.lists];
  lists[1].age = 40;
  this.setState({lists});
}

Hope this helps!

Harshit Agarwal
  • 2,308
  • 2
  • 15
  • 23
0

Consider this:

handle() {
  const { state: { list } } = this;
  const newList = [...list]
  newList[1].age = 40;
    this.setState({ list: newList })
}

The ES6 clone by destruct for Arrays have no side effects!

Sultan H.
  • 2,908
  • 2
  • 11
  • 23