gridcn2.0.0
Scroll mode

Recover from load errors

Show a failed block to the user, report the error, and retry the block after the cause is fixed.

A scroll-mode grid loads many blocks. One block can fail while the others load. The grid keeps the loaded rows, shows an error state, and lets the user retry the failed block.

The demo has two failure buttons. The first one fails the next request once. The second one fails every request until you press "Fix backend". Scroll to unloaded rows to start a request:

100,000 / 100,000 rows loaded · fetching… · cap 2,000 · requests started 0, aborted 0
ID
Name
Email
Score

Report and retry errors

  • Pass onError to useDataGridServerRows to report each failure.
  • When your own code needs the failure, read server.error or server.status.
  • Call server.retry(), or let the user press Retry in the error bar.

This grid reports a failure and replaces the content of the error bar:

"use client";

import { Button } from "@/components/ui/button";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import { useDataGridServerRows } from "@/components/data-grid-server/data-grid-server";

type Order = { id: string; customer: string };

const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer" },
]);

export function OrdersGrid() {
  const server = useDataGridServerRows<Order>({
    mode: "scroll",
    fetchRows: async ({ start, end, signal }) => {
      const query = `offset=${start}&limit=${end - start}`;
      const response = await fetch(`/api/orders?${query}`, { signal });
      const answer = await response.json();
      return { rows: answer.rows, totalRowCount: answer.total };
    },
    onError: (error) => console.error("Could not load rows", error),
  });

  return (
    <DataGrid
      {...server.gridProps}
      columns={columns}
      className="h-96"
      errorState={({ retry }) => (
        <div className="flex items-center gap-2 text-sm">
          <span>Could not load rows.</span>
          <Button type="button" size="sm" onClick={retry}>
            Retry
          </Button>
        </div>
      )}
    />
  );
}

Leave out errorState to keep the built-in error state. With rows, it is a bar under the header. Without rows, it is a message in the body. Both show labels.grid.errorState and a Retry button with the text of labels.grid.errorRetry.

What a failed block does

  • The block stays unloaded. A failed block after block 0 renders as skeleton rows. The grid never marks a failed block as loaded.
  • onError(error) fires once for each failed attempt, and error holds the failure. status is "error" while error holds a failure.
  • A fetchRows that rejects, throws, or resolves without a rows array counts as a failure.
  • The next report of the rendered rows that covers the block requests it again. Scroll away and back to trigger it.
  • Until block 0 lands, the hook requests no other block, on mount and after a spec change. Call retry() or refresh() to load it.
  • An aborted request is no failure and fires no onError. The hook aborts a request on a spec change, a changed row count, refresh(), evict(), or an unmount. It also aborts a block that leaves the keep range: the rendered rows plus overscan plus one block on each side. The first three also clear error.
  • A failed block that leaves the keep range stops counting as an error. When no failure is left, error clears.
  • A throw inside onError or onLoaded does not break the hook. The hook logs it to the console.

When a block fails for good

The hook cannot tell a transient failure from a permanent one, because fetchRows is opaque to it. An expired token or a removed route fails again on every scroll back to the block. The same events fire as for a transient failure.

The error bar shows each failure, so the user sees that the block keeps failing. After you fix the cause, the user presses Retry. server.retry() repeats the failed blocks only. Blocks that already loaded stay loaded, and retry() does nothing without an error.

A sequential source stops at a failed block. retry() repeats that block, and so does the next report of the rendered rows.

Retry after a delay

The hook does not retry on its own. To ride out a short outage, retry inside fetchRows. Wait longer after each attempt. If signal aborts, stop. A request with a cursor repeats the same cursor, so a sequential source keeps its place.

This loader retries a network error, a timeout (408), a rate limit (429), and a server error (500 and above) twice. It sends the cursor of a sequential source. It also sends limit, because the hook drops rows past end - start and the next cursor moves past them:

import type { ServerRowsRequest } from "@/components/data-grid-server/data-grid-server";

const wait = (ms: number, signal: AbortSignal) =>
  new Promise<void>((resolve, reject) => {
    const timer = setTimeout(resolve, ms);
    signal.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(signal.reason);
    }, { once: true });
  });

const isRetryable = (status: number) =>
  status === 408 || status === 429 || status >= 500;

async function fetchWithRetry(url: string, signal: AbortSignal) {
  for (let attempt = 1; ; attempt++) {
    let response: Response;
    try {
      response = await fetch(url, { signal });
    } catch (error) {
      if (signal.aborted || attempt === 3) throw error;
      await wait(500 * 2 ** attempt, signal);
      continue;
    }
    if (response.ok) return response;
    if (!isRetryable(response.status) || attempt === 3) {
      throw new Error(`Request failed with ${response.status}`);
    }
    const retryAfter = Number(response.headers.get("Retry-After"));
    const delay =
      retryAfter > 0 ? Math.min(retryAfter, 30) * 1000 : 500 * 2 ** attempt;
    await wait(delay, signal);
  }
}

export async function loadOrders(request: ServerRowsRequest<string>) {
  const { start, end, cursor, signal } = request;
  const query = new URLSearchParams({ limit: String(end - start) });
  if (cursor !== undefined) query.set("after", cursor);
  const response = await fetchWithRetry(`/api/orders?${query}`, signal);
  const answer = await response.json();
  return { rows: answer.rows, nextCursor: answer.nextCursor };
}

Pass it as fetchRows to useDataGridServerRows<Order, string>({ mode: "scroll", fetchRows: loadOrders }). A retry waits as long as the Retry-After header asks, at most 30 seconds. Any other status fails at once, because a second attempt gets the same answer. The last failure reaches onError and the error bar.

Know when rows land

onLoaded(range) is the success counterpart of onError. When a block resolves, it fires with the row range that the hook wrote. A short answer fires with the smaller row range. A zero-row answer fires nothing.

The grid shows the rows on the next frame. getLoadedRanges() includes the row range at once.

On this page