ProSchedulerSign in

Guides

Loading and saving events

Fetch the events for the visible range as the user navigates, and persist every change optimistically — with a rollback when the server says no.

Load the visible range

ProScheduler draws whatever data holds, so loading is yours to schedule. onPageChange reports the visible range — on mount and after every navigation, view switch or length change — so fetch that range and replace data. lastDay is exclusive. Abort the previous request so a quick run of clicks loads only the page that ends up on screen.

"use client"

import { useRef, useState } from "react"
import { ProScheduler, type SchedulerEvent } from "@andreisaac/pro-scheduler"

export function Bookings() {
  const [events, setEvents] = useState<SchedulerEvent[]>([])
  const request = useRef<AbortController | null>(null)

  return (
    <ProScheduler
      data={events}
      view={{ scheduler: { type: "week" }, agenda: { type: "month" } }}
      // The range on screen — on mount, and whenever it moves.
      onPageChange={async ({ firstDay, lastDay }) => {
        request.current?.abort() // a newer page wins
        const controller = new AbortController()
        request.current = controller
        try {
          const res = await fetch(
            `/api/bookings?from=${firstDay.toISOString()}&to=${lastDay.toISOString()}`,
            { signal: controller.signal },
          )
          setEvents(await res.json())
        } catch {
          // aborted by a newer page
        }
      }}
      …
    />
  )
}

Save changes optimistically

Apply the change to state first so the UI never waits, then persist it. When the request fails, restore the previous array.

const onEventUpdated = useCallback(async (event: SchedulerEvent) => {
  const before = events
  // Optimistic: the move shows immediately.
  setEvents((list) => list.map((e) => (e.id === event.id ? event : e)))

  const res = await fetch(`/api/bookings/${event.id}`, {
    method: "PATCH",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ start: event.start, end: event.end, resource: event.resource }),
  })
  if (!res.ok) setEvents(before) // the server refused: put it back
}, [events])

const onEventCreated = useCallback(async (event: SchedulerEvent) => {
  // The scheduler gives new events a temporary id; swap it for the real one.
  setEvents((list) => [...list, event])
  const res = await fetch("/api/bookings", { method: "POST", body: JSON.stringify(event) })
  const saved: SchedulerEvent = await res.json()
  setEvents((list) => list.map((e) => (e.id === event.id ? saved : e)))
}, [])
// Rules that need the server belong in the "after" callback with a rollback,
// as above. Rules you can check locally belong in the "before" callback,
// which stops the change before anything moves:
onEventUpdate={(event) => !isOutsideOpeningHours(event)}