FullCalendar - React : Using getApi() in datesSet not working (Cannot read properties of undefined (reading 'getApi'))

71 Views Asked by At

I'm using FullCalendar (v6.1.9) with React. I'm using the timeGridDay view and I want to change the slotMinTime and slotMaxTime options depending on what day of the week is displayed (e.g. if Monday is showed, the calendar show 10 am to 6pm, but if it's Saturday we show 8am to 11am).

I'm using datesSet to pass a function that is going to use the calendar API to change slotMinTime and slotMaxTime options:

 datesSet={
    (infoDate) => {
        console.log(calendarRef.current); // It shows me the same object as when I do it in customButtons
        if (infoDate.getDate().getDay() === 6) {
            calendarRef.current.getApi().setOption('slotMinTime', '10:00:00');
            calendarRef.current.getApi().setOption('slotMaxTime', '13:00:00');
        } else {
            calendarRef.current.getApi().setOption('slotMinTime', '16:00:00');
            calendarRef.current.getApi().setOption('slotMaxTime', '19:00:00');
        }
    }
}

The problem is when I'm trying to access to the API, my app crash and I have this error message:

"Cannot read properties of undefined (reading 'getApi') TypeError: Cannot read properties of undefined (reading 'getApi') at Calendar.datesSet (http://localhost:3000/static/js/bundle.js:1377:43)"

The thing I don't understand is, I am able to access the calendar API to create an event through CustomButtons:

customButtons={{
    addEventButton: {
        text: 'Prendre rendez-vous',
        click: function () {
            //TODO open a popup to select a time, create event, do a call to Google Calendar 
            var dateStr = prompt('Enter a date in YYYY-MM-DD format');
            var date = new Date(dateStr + 'T00:00:00'); // will be in local time
            console.log(calendarRef.current)
            if (!isNaN(date.valueOf())) { // valid?
                console.log(calendarRef.current.getApi());
                calendarRef.current.getApi().addEvent({
                    title: 'dynamic event',
                    start: date,
                    allDay: true
                });

            } else {
                alert('Invalid date.');
            }
        }
    }
}} 

And when I'm logging calendarRef.current in datesSet, it's not undefined. I have tried to compare calendarRef.current when I log it in datesSet and customButtons, but it seems identical. I have tried to define my datesSet function above and call it directly in the Calendar Component. But I have always the same error.

Does anyone has an idea about why it's happening and how can I correct it?

0

There are 0 best solutions below