# Server paging and the URL

> Remote paging with or without a reported total, the page kept in the query string, view change events and the data error state.

Canonical: https://salmonui.dev/docs/data-grid/url-paging

With a data source that pages on the server, the grid sends the page and
page size with every read and takes the page count from the
source's `totalRowCount`. A source that cannot count passes
`paging.totalRowCount` instead; it also wins over a reported total.
It has no effect when paging runs in the browser.

## The page in the URL

`paging.syncUrl` keeps the page in the query string. It is opt-in and runs only after mount: the grid reads
`?page=` (or the parameter named by `syncUrl: { param }`), goes to that page,
and writes later page changes with `history.replaceState` (page 1 removes
the parameter), so the back button is not filled with pages. A value that
is not a positive integer is ignored. With a remote source the requested
page is applied once the first result reports the page count. Nothing runs
during render or on the server, so the URL never causes a hydration
mismatch: the server renders `paging.page`; to server-render the requested
page, read the parameter on the server and pass it as `paging.page`.

```tsx
// Next.js App Router page
export default async function Orders({ searchParams }: { searchParams: Promise<{ p?: string }> }) {
  const page = Number((await searchParams).p) || 1;
  return <OrdersGrid paging={{ page, pageSize: 20, syncUrl: { param: 'p' } }} />;
}
```

## View changes

`onViewChange` fires once per committed change of
the displayed rows, after they rendered, with the data row count, the total
across pages and the reason: `data`, `sort`, `filter`, `search`, `group`,
`page` or `refresh`. It never fires for scrolling, focus, selection
or group expansion, and the grid only listens while the handler is bound.
The data source's `onResponse` hook, the `beforeDataBound` counterpart, is
described under [Data sources](https://salmonui.dev/docs/data-grid/data-sources).

## Load errors

When a read fails, the body shows `renderError` with the error, its message
and `retry()`, which reads the source again with the same query; without
`renderError` the grid shows a message and a Retry button.
`onError` reports the failure with `action: 'data'`. Use
"Fail the next request" in the demo, then change the page.

### Live demo: URL-synced paging

Live demo: https://salmonui.dev/demos/data-grid/url-paging

Server paging without a reported total (`paging.totalRowCount`), the page kept in the query string (`paging.syncUrl`), `onViewChange` once per page, and a `renderError` state with retry.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridColumn, type DataSource, type DataGridPaging } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const TOTAL = 1_000;
const orders = createOrders(TOTAL, 11);

const columns: DataGridColumn<Order>[] = [
  { type: 'rowNumber' },
  { field: 'id', header: 'Order', primaryKey: true, width: 120 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 140 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

// The page lives in `?page=` (written with history.replaceState after mount). The source pages on
// the "server" and reports no total, so `totalRowCount` gives the pager its page count.
const paging: DataGridPaging = { pageSize: 20, syncUrl: true, totalRowCount: TOTAL };

/** A server that pages and cannot count, with a switch that fails the next read. */
function createPagedServer(): { source: DataSource<Order>; failNext(): void } {
  let fail = false;
  const source: DataSource<Order> = {
    mode: 'remote',
    read(request) {
      const { page, pageSize } = request.query.paging ?? { page: 1, pageSize: 20 };
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (fail) {
            fail = false;
            reject(new Error('The orders service timed out'));
            return;
          }
          const start = (page - 1) * pageSize;
          resolve({ version: request.version, rows: orders.slice(start, start + pageSize), performed: ['page'] });
        }, 120);
      });
    },
  };
  return { source, failNext: () => void (fail = true) };
}

export default function UrlPagingDemo() {
  const [log, push] = useEventLog();
  // Created once per mounted grid (data sources are initial-only).
  const [server] = useState(createPagedServer);
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={server.failNext}>
          Fail the next request
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders paged on the server, page kept in the URL"
        data={server.source}
        columns={columns}
        paging={paging}
        onViewChange={(e) => push(`view: ${e.reason}, ${e.rowCount} of ${e.totalRowCount} rows (${e.source})`)}
        onError={(e) => push(`error (${e.action}): ${e.error.message}`)}
        renderError={({ message, retry }) => (
          <div className="demo-error" role="alert">
            <strong>Orders are unavailable.</strong> {message}.{' '}
            <Button variant="outline" onClick={retry}>
              Try again
            </Button>
          </div>
        )}
        height={360}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
      />
      <p className="demo-status">Change pages and watch the address bar; reload to come back to the same page.</p>
      <EventLog entries={log} label="View changes and errors" />
    </>
  );
}
```

## API reference

See [`DataGridPaging`](https://salmonui.dev/docs/reference/data-grid/DataGridPaging)
(`syncUrl`, `totalRowCount`),
[`DataGridViewChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridViewChangeEvent)
and [`DataGridDataErrorContext`](https://salmonui.dev/docs/reference/data-grid/DataGridDataErrorContext)
in the API reference.
