gridcn2.0.0
Data modes

Move from client rows to server rows

Replace a local data array with useDataGridServerRows, and check each grid feature that changes when your server owns the rows.

A grid with a local data array sorts, filters, and copies every row in the browser. When the browser cannot hold the result, your server must own it. This page replaces data with useDataGridServerRows and lists each feature that changes. Each line links the page that owns the detail.

Before you start, pick pages mode or scroll mode on Compare data modes. Then install the server add-on:

pnpm dlx shadcn@latest add @gridcn/data-grid-server

Replace the data

  1. Put the rows behind an API that takes the spec and a page or a row range. Server rows contract has the request and the answer.
  2. Remove data, defaultData, and onDataChange from the grid.
  3. Pass fetchRows to useDataGridServerRows. Move getRowId into the hook options too, unless the row id is in the id field.
  4. Move onSave into the hook options. Move your own onDataChange there too.
  5. Spread server.gridProps onto DataGrid. Keep columns and your other props.
  6. In pages mode, spread server.pager onto DataGridPaginationBar.

This grid fetches blocks of orders in place of a local data array:

"use client";

import {
  DataGrid,
  defineColumns,
  type DataChange,
} from "@/components/data-grid/data-grid";
import {
  useDataGridServerRows,
} from "@/components/data-grid-server/data-grid-server";

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

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

async function save(change: DataChange<Order>) {
  const response = await fetch("/api/orders/changes", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(change.ops),
  });
  if (!response.ok) throw new Error("Save refused");
}

export function OrdersGrid() {
  const server = useDataGridServerRows<Order>({
    mode: "scroll",
    fetchRows: async ({ spec, start, end, signal }) => {
      const response = await fetch("/api/orders/query", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ spec, start, end }),
        signal,
      });
      const answer = await response.json();
      return { rows: answer.rows, totalRowCount: answer.total };
    },
    onSave: save,
  });

  return <DataGrid {...server.gridProps} columns={columns} className="h-96" />;
}

The hook sets sortMode="server", filterMode="server", totalRowCount, and checkedRowsLifetime="across-filters" in gridProps.

Check what changes

FeatureLocal arrayServer rows
SortThe grid sorts data. sortCompare and the cell type compare the values.Your server sorts. sortCompare does not run.
FilterThe grid runs filter.match and the operators.Your server filters. filter.match does not run. Without fetchFilterValues, the header filter lists the values of the loaded rows.
Quick searchHighlights matches in every row.Puts the text in spec.searchText. The box highlights matches in the rows that come back.
Copy and pasteEvery displayed row. On a paged grid, the shown page.The rows that data holds. In scroll mode, a copy gives empty cells for rows that are not loaded, and a paste skips them.
Checked rowsThe checks cover data.actions.selectAllMatching() checks the whole result. Send useDataGridSelectedRows() to your server.
ExportWrites every row.Writes the rows the grid holds. Pass a source to write the whole result.
TotalsuseDataGridAggregate totals every row.DataGridServerAggregateReporter asks your server for the totals.
SavesonSave on the grid.onSave in the hook options. The hook fetches again after the saves settle.
Undo and redoWrites the old values to data.An undo is one more change that onSave sends.
Row operationsChange data.Send each insert, delete, and move to your API.
Live pushesupdateCells keeps the row in place and sets viewStale. reconcileView() or reorder: "immediate" moves it.The row keeps its place and turns stale. Call server.reshape(), or set reshapeDelayMs, so that the server places it again.
URL state<DataGridUrlState> restores the sort, and the filter and search text when its spec lists them.<DataGridUrlState> restores the spec, and the first request of the hook carries it. Your server applies it.

Check the server

  • Treat the request as untrusted input. Pass body.spec through parseServerSpec, and bound the page or the row range. See Check the spec on your server.
  • Port each custom sortCompare and filter.match to your query. The grid does not run them in server mode.
  • Make the sort order unique. See Sort on the server.
  • Answer with totalRowCount. A source without a count answers with nextCursor or hasMore. See Load without row count.

Test the move

  1. Sort and filter each column that you sorted or filtered before. Compare the order with the old client result.
  2. Scroll or page to the end. Check the row count and the last row.
  3. Edit, paste, and undo a cell. Check that the change reaches your API, and that a refusal reverts the cell. See Handle refused saves.
  4. Make a request fail. Check the error state and the Retry button. See Recover from load errors.
  5. Check all matching rows, uncheck one, and send the selection to your server.
  6. Export the whole result through a source.

Result: the grid shows the rows of your server, and each feature you use has a server path.

On this page