Main problem: I am fight against updating array of object in react big calendar. Problem is when I change position of one of object, all of them change start and end date like this one example.
I am pretty sure that this is because I wrote bad example of updating method of array of object
const resizeEvent = ({ event, start, end }) => {
const nextEvents = allEvents.map(existingEvent => {
if (existingEvent.id === event.id) {
existingEvent.start = start;
existingEvent.end = end;
}
return existingEvent;
});
setAllEvents(nextEvents)
};
CodePudding user response:
Not sure what exactly the structure you have for allEvents
and I guess you may want to copy the existingEvent
before mutating ....
I mean something as below (commented about shallow copy)
const resizeEvent = ({ event, start, end }) => {
const nextEvents = allEvents.map((event) => {
const existingEvent = {... event}; // shallow copy to mutate
if (existingEvent.id === event.id) {
existingEvent.start = start;
existingEvent.end = end;
}
return existingEvent;
});
setAllEvents(nextEvents);
};
CodePudding user response:
use the callback in setState with find method
setAllEvents((prev) => {
const existingEvent = allEvents.find(existingEvent => existingEvent.id === event.id)
if(existingEvent) {
existingEvent.start = start;
existingEvent.end = end;
return [
...prev,
item
]
}
return prev
})