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'.
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'.
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)
})
)
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')
You can use map. for example:
const newData = data.map(val => {
if(val.id === id) {
return {...val, name: 'new name'};
}
return val;
}
You would have to update the associated variable in the state:
this.state.values[1].age = 10;
this.setState({
values,
});