Reputation: 1994
I have the below code where I am trying to update setState with few properties modified in array of objects
onClick(index) {
let tmp = this.state.daysOfWeek;
tmp[index].active = !tmp[index].active;
if (tmp[index].active === true) {
tmp[index].className = "selectedDay";
} else {
tmp[index].className = "remSelectedDay";
}
this.setState({ daysOfWeek: [...this.state.daysOfWeek, tmp]})
}
Here tmp is modified array of objects. If I use spread operator then the arry of objects are concatinated wiht tmp.
How could I update the current state with array of objects ?
Upvotes: 0
Views: 117
Reputation: 10873
A combination of map
and the functional form of setState
will allow you to correctly update the array without directly modifying the state:
onClick(index){
this.setState(state => {
return {
daysOfWeek: state.daysOfWeek.map((day, i) => {
if (i === index) {
return {
...day,
active: !day.active,
className: day.active ? 'remSelectedDay' : 'selectedDay'
}
}
return day;
})
}
})
}
Upvotes: 1
Reputation: 11930
onClick (index) {
const { daysOfWeek } = this.state // for example: [1, 2, 3, 4, 5], index = 1
this.setState({
daysOfWeek: [
...daysOfWeek.slice(0, index), // [1]
{
...daysOfWeek[index], // this is 2
active: !daysOfWeek[index],
className: daysOfWeek[index] ? 'selectedDay' : 'remSelectedDay'
},
...daysOfWeek.slice(index + 1) // [3, 4, 5]
]
})
}
Upvotes: 0