gridcn2.0.0
Rows and live data

Change server rows

Insert, duplicate, delete, and move rows in a grid that loads rows from a server, and send each change to your API from onSave.

Row operations change the rows of the grid. Each one reaches onDataChange and onSave as an insert, delete, or move operation with a row id. On a server grid, send those operations to your API and let a refusal revert them.

useDataGridServerRows sets checkedRowsLifetime="across-filters". A checked row stays checked after a page change or a filter hides it. If any row is checked, the operations act on the checked rows that the view shows and leave the hidden checked rows alone. onBeforeDeleteRows gets their number as hiddenCount.

Enable the operations

Insert needs createRow. Duplicate needs duplicateRow. Delete needs nothing. Give each new row an id that the server accepts. createRow and duplicateRow are props of the grid, and onSave is an option of the hook:

"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 failed: ${response.status}`);
}

export function OrdersGrid() {
  const server = useDataGridServerRows<Order>({
    mode: "scroll",
    fetchRows: async ({ start, end, spec, 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}
      createRow={() => ({ id: crypto.randomUUID(), customer: "", total: 0 })}
      duplicateRow={(row) => ({ ...row, id: crypto.randomUUID() })}
      className="h-96"
    />
  );
}

Without createRow or duplicateRow, the matching operation does nothing and warns in development. The context menu hides the matching items.

Send the operations

change.ops holds one operation per row. Revert or refetch after a save maps insert to a create request, delete to a remove request, and update to a patch. It sends all move operations of one change in one request, because the server must apply them as a batch.

If the server refuses an insert, the grid removes the row. If it refuses a delete, the grid brings the row back. See Handle refused saves.

Take the id from the server

The grid keeps the id that createRow returns until you swap it.

After the server answers, call actions.replaceRowId(oldId, row) with the server row. See Save edits. Or let createRow return a promise that creates the row first. duplicateRow can return a promise too. The grid holds the operation until the promise resolves, and a rejection cancels it.

In this demo, a new row gets a client id, and the mock server answers with its own id. The log shows the "id-swap" change:

Add a row. It starts with a client id. When the server answers, the grid swaps in the server id and keeps the row in place.

ID
Name
City
srv-101
Ada
Berlin
srv-102
Grace
Hamburg
srv-103
Linus
Munich
  • No change yet.

While a createRow promise is pending, the next insert does nothing. While a duplicateRow promise is pending, the next duplicate does nothing. If the anchor row left the grid or the grid turned readOnly before the promise resolves, the grid drops the operation.

If the promise creates the row on the server, skip the insert operation in onSave, because the server already has the row.

Delete rows you know

A scroll-mode grid holds unloaded rows as holes. If their target touches a hole, deleteRows, deleteRowsAt, duplicateRows, duplicateRowsAt, insertRow, and insertRows do nothing. The target is every row of a delete, every source row of a duplicate, and the anchor row of an insert. One hole cancels the whole request. The grid writes nothing, calls no onDataChange, and warns once in development.

deleteRows skips an id that matches no row and deletes the rest. A placeholder id matches a hole, so it cancels the whole request. Drop those ids before you call it.

isPlaceholderRowId(id) tells a placeholder from a real id. reorderRows does nothing while any row is unloaded.

Select all in a scroll-mode grid checks the holes too. To delete rows that you know, pass their ids, as in actions.deleteRows(["o-17", "o-18"]). Get actions from useDataGridActions() in a component inside DataGridProvider, next to DataGridRoot.

To delete every row of a filtered server result, call your own endpoint and run server.refresh().

After a row operation in a scroll-mode source with a row count, the hook refreshes the rendered rows on the next frame. The refresh keeps a row with a pending save or an open edit. A pending insert stays hidden while the answer holds a row in its slot. A pending delete stays gone. The hook refreshes again when the last insert or delete save settles.

Refresh after the save

In pages mode, the operations act on the current page. When the last pending insert or delete settles, the hook loads the page again, unless refreshAfterSave is false. Then call refresh() yourself.

Pass onSave to useDataGridServerRows and the hook refreshes after the saves settle (refreshAfterSave, default "settled"). Or call server.refresh() after the onSave promise settles to pick up server-computed values. A refresh keeps a pending insert, so the page can hold more than pageSize rows until the save settles.

Confirm a delete

onBeforeDeleteRows runs before every delete, from the shortcut, the context menu, and deleteRows or deleteRowsAt. A deleteRows call with source: "stream" skips the gate. Return false or a promise of false to cancel. Without the prop, a delete runs at once.

When "select all matching" is on, the Delete, Duplicate, and Move shortcuts do nothing. See Select server rows.

Move rows

reorderRows(rows, to) and moveRowsBy(rows, delta) emit one move operation per moved row. Each operation holds from and to in the loaded rows, plus afterRowId and beforeRowId for the neighbors. Send the ids when your server holds rows that the grid has not loaded. The grid blocks them while a sort is active, also a server sort. A client-side filter, a readOnly grid, or an unloaded row blocks them too. A server filter does not. Your server decides the order of the next answer.

On this page