I have an issue because when I'm using my function setEvents to update my state events's value (using my setEvents function), my page isn't refreshing.
Look here :
function App() {
const [events, setEvents] = useState([]);
const clickDate = (e)=>{
const newEvents = events
const event = {
id: 'test',
title: 'my event',
start: e.dateStr
}
newEvents.push(event);
setEvents(newEvents);
console.log(events);
}
return (
<div className="App">
<FullCalendar
plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
initialView='timeGridWeek'
weekends = {weekEnd}
selectable = {true}
allDaySlot = {false}
eventConstraint = "businessHours"
dateClick = {clickDate}
events = {events}
/>
</div>
);
}
export default App;
My "console.log(events)" display correctly the new events after having used my clickDate function, but the page is not refreshing.
Does anybody have any suggestions?
Thanks you all!
CodePudding user response:
Technically you're mutating state here:
newEvents.push(event);
Which is kind of hiding in some over-complicated logic for just setting a new state value. And when you update state, it's to a reference to the same array (that you've now mutated).
Simplify what you're doing. Update the state to a new array constructed from the elements of the previous one plus the new element:
const clickDate = (e)=>{
setEvents([...events, {
id: 'test',
title: 'my event',
start: e.dateStr
}]);
}