Skip to content

Connect a JavaScript Scheduler to an API with optimistic updates and rollback ​

You move a workshop to 11:00. The server saves it, but the reply never reaches the browser. The safest next step is to look up that operation’s receipt. A confirmed rejection rolls the edit back. A missing reply leaves it pending until the client can recover the outcome.

This example connects RevoGrid Scheduler to a local API that loads the visible date range and saves edits with receipts. The screen uses React. The remote configuration and HTTP protocol also apply to JavaScript, Vue and Angular.

Run the API example ​

The example app and API use Node 24.13 or later for SQLite.

sh
git clone https://github.com/revolist/revogrid-docs.git
cd revogrid-docs/examples/scheduler-workflows
pnpm install --ignore-scripts
pnpm dev

Open http://127.0.0.1:49313/?example=remote. The app sends requests to a local SQLite-backed API. Select Reset demo before each scenario.

ActionExpected result
Load the pageTwo bookings appear; Activity records the requested interval
Move the workshop from 09:00 to 11:00Its canonical interval becomes 11:00–13:00
Enable Reject next save, then move itThe rejected proposal returns to its previous interval
Enable Commit next save, then lose its response, then move itThe new position remains pending; Unknown becomes 1
Select Recover unknown saveThe stored accepted receipt confirms the new interval; Unknown returns to 0

The Move workshop to 11:00 button performs the same documented edit operation deterministically. You can also drag the bar; the remote persistence path is shared.

Load events that intersect the requested range ​

The request contains civil dateRange values, time zone, filters, visible resource IDs and half-open instant bounds. Pass the supplied abort signal to fetch. Use the supplied instants instead of constructing midnight boundaries in the browser's local time zone.

ts
import type { EventSchedulerRemoteRangeRequest } from '@revolist/scheduler';

async function loadEvents({
  startDateTime,
  endDateTime,
  resourceIds,
  signal,
}: EventSchedulerRemoteRangeRequest) {
  if (!startDateTime || !endDateTime) throw new Error('Missing range bounds.');
  const params = new URLSearchParams({
    start: startDateTime,
    end: endDateTime,
  });
  for (const id of resourceIds ?? []) params.append('resource', String(id));

  const response = await fetch(`/api/events?${params}`, { signal });
  if (!response.ok) throw new Error(`Load failed (${response.status}).`);
  return response.json();
}

Use this callback as eventScheduler.remote.loadEvents. The endpoint returns { events, rangeComplete: true } because this example returns every matching event for the requested resource set and interval.

Its SQL selects intersections:

sql
WHERE start_ms < :requested_end
  AND end_ms > :requested_start

Filtering only on start_ms >= requested_start loses events that started earlier and continue into the visible window. The actual implementation also binds the allowed resource IDs, validates dates and caps the requested interval at 31 days. It does not interpret filter strings as SQL.

The resource list and availability use separate loadResources and loadAvailability hooks. For larger datasets, implement cursor/resource paging and the other remote loaders rather than returning every resource. Map filters to an explicit backend schema and enforce authorization before querying.

Choose how the Scheduler saves edits ​

Loading and saving are independently configurable. Choose one persistence path for each edit:

IntegrationApplication suppliesScheduler supplies
Final-event listenersThe complete save/retry/reconciliation policyLocal editing and accepted mutation events
remote.commitMutationA callback returning acceptance or rejectionPending presentation and rejection rollback
remote.commandsSubmission, durable receipts and receipt lookupOrdered commands, unknown outcomes and recovery APIs

Do not install an additional save listener when commitMutation or commands already sends that edit. Final mutation events are useful for observation and framework synchronization; they cannot cancel an accepted local change.

For commitMutation, return { accepted: true, event: canonicalEvent } for a single record, or { accepted: false, message } for a definitive refusal. events means a complete event collection, so a one-record events array is not an incremental patch. The saving contract documents both forms.

Configure optimistic projection and rollback ​

The runnable app places these settings directly under remote:

ts
remote: {
  enabled: true,
  mode: 'remote',
  optimistic: true,
  rollbackOnError: true,
  refreshPolicy: 'changed-range',
  query: { retry: 0, refetchOnWindowFocus: false },
  // The full example adds its loaders and commands here.
}

An optimistic proposal updates immediately. A definitive rejection restores the rejected change while preserving later edits. After acceptance, changed-range requests authoritative data for affected dates. With optimistic: false, canonical data and history wait for acceptance, although a pending move can still be displayed at its proposed destination.

Read query settings control cache freshness and refetch behavior. They do not retry writes or choose rollback behavior. The example disables read retries and focus refetch to make the walkthrough easy to inspect; applications can opt into the documented polling and reconnect policies.

Treat a missing response as an unknown outcome ​

Suppose the server saves 11:00–13:00, then the connection closes before the response reaches the browser. Automatically restoring 09:00–11:00 would make the screen disagree with the database. Retrying with a new operation ID could apply a write twice.

The legacy commitMutation callback treats a thrown error as rejection. The receipt-based remote.commands path distinguishes the outcomes:

The sample's command configuration reads the prior event revision and submits a compact version of the captured envelope. Here is the transport portion:

ts
commands: {
  resourceId: 'demo-bookings',
  getExpectedRevision: ({ previousEvent }) =>
    previousEvent?.metadata?.revision as string | undefined,
  async submit(envelope, { signal }) {
    const { action, eventId, event } = envelope.command;
    const response = await fetch('/api/commands', {
      method: 'POST',
      signal,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...envelope,
        command: { action, eventId, event },
      }),
    });
    if (!response.ok) throw new Error('Write response unavailable.');
    return response.json();
  },
  async recover(envelope, { signal }) {
    const response = await fetch(
      `/api/receipts/${encodeURIComponent(envelope.operationId)}`,
      { signal },
    );
    if (!response.ok) throw new Error('Receipt unavailable.');
    return response.json();
  },
}

The full source adds the two failure-injection headers used by the walkthrough. They belong only to the local demonstration endpoint.

An accepted receipt includes the same operationId, a revision and canonical changes.event. A rejected receipt supplies a message. A conflict receipt supplies the authoritative event and current revision. An unknown receipt reports that no definitive outcome is available yet. See the command protocol for exact types and validation rules.

Store the booking and its receipt atomically ​

The example's backend checks resource availability, overlap and the expected record revision inside a SQLite transaction. It writes the updated booking and receipt before committing. Receipt lookup reads the same durable database.

Submitting an identical operation ID and payload returns the recorded outcome. Reusing an operation ID with a different payload is rejected. This is application code; Scheduler does not install a receipt service or database schema.

On the client, unknown commands stay pending and hold subsequent receipt commands in order. The recovery button reads scheduler.getRemoteState().unknownMutationIds and calls:

ts
for (const requestId of scheduler.getRemoteState().unknownMutationIds ?? []) {
  await scheduler.recoverRemoteMutation(requestId);
}

These are Scheduler mutation request IDs, not backend operation IDs. The plugin maps each request to its captured command for the recover callback. Recovery performs a receipt lookup; it does not submit another write. The example does not enable retries. Only set idempotent: true and use retryRemoteMutation when the backend contract supports retrying the identical envelope.

Verify state after failure and recovery ​

Run pnpm test. Tests assert a rejected concurrent booking leaves one stored reservation, stale revisions return authoritative data, receipts survive closing and reopening SQLite, and a response lost after commit is recovered as accepted. They also verify that reading 11:30–12:30 includes an event that started at 11:00.

During a manual drag, inspect both the visible position and the server's event data. Pending styling alone does not prove a save succeeded. A cancelled request likewise does not undo a write already committed by the server.

This example recovers unknown commands while the mounted scheduler still owns them. Recovery after a browser reload or destroyed view needs an application-owned persisted command ledger; the plugin's in-memory request list is insufficient. Shared read caches should also be scoped to the same dataset, schema, tenant and authorization boundary.

The local server intentionally has no login and accepts one resource per event. Before deploying a backend, add authenticated scope, per-resource authorization, request/receipt schema checks and domain-specific rules. For the booking transaction itself, continue with preventing double booking. For staffing demand, see the React shift planner.

Explore RevoGrid Scheduler, the live demos, and the complete remote-data guide.