-1

I have list of Map in my state in my React app. Ex:

item : [ { name: 'abc', age: '10' }, { name: 'xyz', age: '2' }, { name: 'sdf', age: '6'} ]

How would I update the state, if I want to just change set 'age': 10 for name 'xjz'.

Treycos
  • 7,373
  • 3
  • 24
  • 47
hash
  • 3
  • 3
  • 3
    Possible duplicate of https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs – FuzzyTree Jan 26 '19 at 20:47
  • What have you tried? One way you can do it is using [findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) with the condition you need to match and then update the object at that `index`. Also, name `xjz` is not available on your example. – Shidersz Jan 26 '19 at 20:51

4 Answers4

0

You should create a new array mapping to old one with new values:

const initial = [
  { name: 'abc', age: '10' },
  { name: 'xyz', age: '2' },
  { name: 'sdf', age: '6'}
]

const updated = initial.map(element =>
                  element.name === 'xyz'
                    ? { ...element, age: 10 }
                    : element
                )
                
console.log(updated)
/*
[
  {
    "name": "abc",
    "age": "10"
  },
  {
    "name": "xyz",
    "age": 10
  },
  {
    "name": "sdf",
    "age": "6"
  }
]
*/

Remember that if you need the previous state to compute the next one, you need to call setState passing a function that takes the previous state as the first argument:

this.setState(
  prevState => ({
    // ... the new state here (where you map over your items)
  })
)
0xc14m1z
  • 3,675
  • 1
  • 14
  • 23
0

The easiest solution would be to map your array and only replace the item where your condition matches :

this.setState(prev => ({
    item: prev.item.map(item => item.name === 'xjz' ? { ...item, age: '10' } : item)
}))

In a class function :

changeValue = name => {
    this.setState(prev => ({
        item: prev.item.map(item => item.name === name ? { ...item, age: '10' } : item)
    }))
}

changeValue('xyz')
Treycos
  • 7,373
  • 3
  • 24
  • 47
-1

You can use map. for example:

const newData = data.map(val => {
  if(val.id === id) {
    return {...val, name: 'new name'};
  }
  return val;
}
Umair Farooq
  • 1,763
  • 13
  • 16
-1

You would have to update the associated variable in the state:

this.state.values[1].age = 10;

this.setState({
    values,
});
Jay
  • 841
  • 1
  • 8
  • 19