# Event sources

> Load events from your server for the visible range with an async eventSource, cancel stale requests, show loading state and handle errors.

For calendars with more events than you want to load up front, such as years of bookings or a whole company's meetings, give the calendar an `eventSource`. It is an async function the calendar calls with the visible range, so you only fetch what the user is looking at.

## A basic source

```ts
import { createCalendar, type EventSourceRequest } from '@birchui/calendar';

async function loadVisits({ start, end, timeZone, signal }: EventSourceRequest) {
  const query = new URLSearchParams({ from: start.toISOString(), to: end.toISOString(), tz: timeZone });
  const response = await fetch(`/api/site-visits?${query}`, { signal });
  if (!response.ok) throw new Error(`Site visits failed to load (${response.status})`);
  return response.json();
}

const calendar = createCalendar(document.getElementById('visits-calendar')!, {
  view: 'month',
  timeZone: 'America/Chicago',
  eventSource: loadVisits,
});
```

The request has:

| Field | Description |
| --- | --- |
| `start`, `end` | The visible range as `Date`s, `end` exclusive. The month view covers whole weeks, so it includes days from the neighbouring months. |
| `timeZone` | The display zone as an IANA name. When no `timeZone` option is set, this is the browser's zone, resolved for you. |
| `signal` | An `AbortSignal`, aborted when the request is no longer needed. Pass it to `fetch`. |

Return an array of events in the same shape as the `events` option. Anything that is not an array is treated as an empty list.

## When the source is called

- Once when the calendar is created.
- Whenever the visible range changes: `next()`, `prev()`, `today()`, `gotoDate()`, switching views, or toolbar and keyboard navigation.
- When you call `refetch()`, which reloads the current range even if it has not changed and returns a promise that settles when loading has finished.

Returning to the range that is already loaded does not call the source again.

Call `refetch()` yourself in these cases, because they do not trigger a load on their own:

- after you replace the source with `update({ eventSource })`;
- after you change the display zone with `update({ timeZone })`, if your server's answer depends on it;
- after your own code changed data on the server, such as an event created in a dialog.

```ts
await api.post('/api/site-visits', newVisit);
await calendar.refetch();
```

## Stale requests

When the user clicks through months quickly, the calendar aborts the previous request through its `signal` before starting the next one, and it ignores the result of any request that is no longer current. Only the latest range ever reaches the screen, even if your server answers out of order. Rejections caused by an abort are ignored as well.

If your data layer does not support `AbortSignal`, the calendar still discards stale results; you only lose the network saving.

## Loading state

While a request is pending:

- `loading` fires with `{ isLoading: true }`, and again with `{ isLoading: false }` when it settles;
- `isLoading()` returns `true`;
- the root element has the class `lq-cal--loading` and `aria-busy="true"`;
- the toolbar shows the `loading` label next to the title, announced through a status region.

```ts
calendar.on('loading', ({ isLoading }) => {
  spinner.hidden = !isLoading;
});
```

Change the announced text with `labels: { loading: 'Loading site visits' }`.

## Errors

When the source rejects or throws, the calendar logs the error with `console.error`, ends the loading state and keeps showing the events from the last successful load. It does not retry. To show an error in your interface, catch it inside the source and rethrow:

```ts
const calendar = createCalendar(container, {
  view: 'week',
  eventSource: async (request) => {
    try {
      errorBanner.hidden = true;
      return await loadVisits(request);
    } catch (error) {
      if (!request.signal.aborted) {
        errorBanner.textContent = 'Site visits could not be loaded. Check your connection and try again.';
        errorBanner.hidden = false;
      }
      throw error;
    }
  },
});

retryButton.addEventListener('click', () => void calendar.refetch());
```

## Combining a source with local events

`events` and `eventSource` can be used together. Events passed through `events`, `setEvents()` and `addEvent()` are kept as a local list, and the latest result of the source is kept as a separate list that is replaced on every load. The calendar shows both.

This is useful for holidays or company-wide closures that ship with your app, next to per-user data from the server:

```ts
createCalendar(container, {
  view: 'month',
  events: [
    { id: 'holiday-2026-12-25', title: 'Office closed: Christmas Day', start: '2026-12-25', allDay: true, editable: false },
    { id: 'holiday-2027-01-01', title: "Office closed: New Year's Day", start: '2027-01-01', allDay: true, editable: false },
  ],
  eventSource: loadVisits,
});
```

Keep the two lists apart:

- Do not `addEvent()` an event that your server will also return, or it appears twice after the next load. Save it on the server and call `refetch()` instead.
- Drags and resizes of loaded events change the loaded copy only. Save them in your `eventDrop` and `eventResize` listeners, or the next load brings back the server's version. See [Interactions](https://docs.birchui.com/calendar/interactions.md#save-and-roll-back-on-failure).
- `getEvents()` returns both lists.

## Caching

The source is called for every new range, so add your own cache when users move back and forth a lot:

```ts
const cache = new Map<string, Promise<SiteVisit[]>>();

const cachedVisits = (request: EventSourceRequest) => {
  const key = `${request.start.toISOString()}|${request.end.toISOString()}|${request.timeZone}`;
  if (!cache.has(key)) {
    const pending = loadVisits(request).catch((error) => {
      cache.delete(key);
      throw error;
    });
    cache.set(key, pending);
  }
  return cache.get(key)!;
};
```

Clear the cache before calling `refetch()` when you know the data changed.

## Next steps

- [Time zones](https://docs.birchui.com/calendar/time-zones.md) for how returned times are read.
- [API and events](https://docs.birchui.com/calendar/api.md) for `refetch`, `isLoading` and `loading`.
