javascriptfullcalendarfullcalendar-6

How can I retrieve only the 'next event' in console.log?


calendar.getEvents(); 

The above will of course list all events stored in client-side memory. Is there a similar command that will list only the 'next' event that will occur from that time forward?

I can't seem to find anything in the FullCalendar.io documentation about specifically getting the next event.


Solution

  • Yes, there is no in-build method in FullCalendar.io, that directly retrieves only the "next" event. However we can achieve this by implementing a custom function that filters and sorts the events to find the next one.

    Here is what we can try.

    function getNextEvent() {
      const now = new Date()
      const events = calendar.getEvents()
    
      /* Filter events to include only those events which start in the future */
    
      const futureEvents = events.filter(event => event.start > now)
    
      /** Sort Future events by their time */
      futureEvents.sort((a, b) => a.start - b.start)
    
      // Return the next event (which will be first event in the sorted list) or null if no future events
      return futureEvents.length > 0 ? futureEvents[0] : null
    }
    
    
    const nextEvent = getNextEvent()
    
    if (nextEvent) {
      console.log('Next event:', nextEvent.title, 'at', nextEvent.start)
    } else {
      console.log('There are no upcoming events.')
    }