For example if a state is like this
state={
reports:[{name:'nadib',age:23},{name:'nadib2',age:24}]
}
how can I change nadib2
to john with setState method?
For example if a state is like this
state={
reports:[{name:'nadib',age:23},{name:'nadib2',age:24}]
}
how can I change nadib2
to john with setState method?
You can use the functional setState
syntax and create a copy using map
to prevent mutation of the current state.
Then inside the loop, return the original object if you do not wish to modify. For the object that you need to modify, you could find it with a ternary operator and copy all existing keys, optionally modifying the other keys like shown.
this.setState(prevState => {
return {
reports : prevState.reports.map(item =>
item.name === 'nadib2' ? ({...item, name: 'john'}) : item)
};
});