I have a React app with an interface that allows users to select a date and time slot. I have a top level object that maintains the state, which might look like this:
this.state = {
days: [{
date: '12-13-2022',
time_slots: [{
start: '10 am',
end: '11 am',
selected: false
},{
start: '1 pm',
end: '3 pm',
selected: false
}]
}, {
date: '12-14-2022',
time_slots: [{
start: '10 am',
end: '11 am',
selected: false
}
}]
}
When a user clicks on a time slot, I want to update the selected
property to true
.
So far I have this, but I think I'm mutating the state, which is bad practice.
slotClicked(day_index, slot_index) {
let state = this.state.days[day_index].time_slots[slot_index].selected = true;
this.setState({state});
}
How might I update the state in an efficient (in terms of re-rendering) and immutable way?
You have to deep clone your array, in opposition to other answers:
slotClicked(day_index, slot_index) {
// If you prefer you can use lodash method _.cloneDeep()
const newDays = JSON.parse(JSON.stringify(this.state.days));
newDays[day_index].time_slots[slot_index].selected = true;
this.setState({days: newDays});
}
If you do not deep clone your array, the time_slots
array will be copied by reference and mutanting it will mutate original array in state.
You can make use of Array.map function as,
slotClicked(day_index,slot_index){
let current_state = this.state;
this.state.days.map((days,days_index) => {
if(days_index===day_index){
// console.log("day",days);
let newSlot = '';
days.time_slots.map((time_slot,slots_index)=>{
if(slots_index===slot_index){
// console.log("time",time_slot);
newSlot = Object.assign({},time_slot,{selected:true});
}
})
// console.log("new slot",newSlot);
days.time_slots[slot_index] = newSlot;
this.setState({days:current_state},()=>{
console.log(this.state);
});
}
});
}
To update a deeply nested data, you can use https://github.com/debitoor/dot-prop-immutable or something similar. In plain Javascript, it will be more verbose like below
const state = this.state;
const newState = {
...state,
days: [
...state.days.slice(0, day_index),
{
...state.days[day_index],
time_slots: [
...state.days[day_index].time_slots.slice(0, slot_index),
{...state.days[day_index].time_slots[slot_index], selected: true},
...state.days[day_index].time_slots.slice(slot_index + 1)
]
},
...state.days.slice(day_index + 1)
]
}
try this, here we are cloning previous state and updating the new one
slotClicked(day_index, slot_index) {
let newStateDays = [...this.state.days]
newStateDays[day_index].time_slots[slot_index].selected = true;
this.setState({days: newStateDays});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.