gridcn2.0.0
Save to a server

Save edits

Send each edit, paste, fill, and row change of the grid to your API from onSave, and read the saving status of a row.

The grid applies an edit at once. onSave sends the same change to your server. The grid calls it with a DataChange after onDataChange. If you return a promise, the grid tracks the save and reverts a refused change.

Edit a name. Type "Al" and press Enter: after the delay the server refuses it and the cell goes back.

Name (3+ characters)
City
Person 0
Hamburg
Person 1
Berlin
Person 2
Hamburg
Person 3
Berlin
Person 4
Hamburg
Person 5
Berlin
Person 6
Hamburg
Person 7
Berlin
Person 8
Hamburg
Person 9
Berlin
Person 10
Hamburg
Person 11
Berlin
All changes saved

Send a change

  1. Pass onSave to the grid.
  2. Send change.ops to your API. Each operation has a type and a rowId.
  3. Return the promise of the request.
  4. If the request fails, throw or reject.

This grid keeps its rows and saves every change:

"use client";

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

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

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

async function save(change: DataChange<Order>) {
  const response = await fetch("/api/orders", {
    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({ rows }: { rows: Order[] }) {
  return (
    <DataGrid
      defaultData={rows}
      columns={columns}
      onSave={save}
      onSaveRejected={() => alert("The server refused the change.")}
    />
  );
}

defaultData seeds the rows once, and the grid owns them. With controlled data, write each change into your state in onDataChange, or the grid drops the edit.

A request that fails reverts the whole change. Then onSaveRejected runs once per refused change with { change, rejected, error }. To revert only the refused rows, see Handle refused saves.

What onSave receives

  • A row with a save in flight carries aria-busy="true". A refused save reads through the live region (labels.grid.saveRejected).
  • A readOnly grid writes nothing for a cell edit, so onSave does not run.
  • A function that returns a promise sets the status of the rows. If it returns nothing and does not throw, the grid sets no status and cannot refuse the change. A synchronous throw refuses it.

The source of a change names its origin. onSave receives these values, and never "rollback", "stream", or "id-swap":

sourceOrigin
"edit"A cell edit, or updateCells with source: "edit".
"paste"A paste.
"fill"A fill.
"delete"A cell clear with the Delete key.
"cut"A cut (Ctrl/Cmd+X).
"row-operation"An insert, a duplicate, a delete, or a move of rows.
"import"An import.
"history"An undo or a redo.
"merge"The row that resolveSaveConflict commits.
"replace"A find and replace.
"app"An entry that your code records with record().

Read the save status

While the promise is pending, each row of the change is saving. The row element carries data-save-status="saving". A refused row carries failed until the next save of that row or a call of actions.clearSaveStatus().

  • useDataGridRowSaveStatus(rowId) returns "saving", "failed", or undefined.
  • useDataGridPendingSaveCount() returns the number of onSave promises that have not settled.

Call both hooks under DataGridProvider.

onSave takes a second argument, { actions, signal }. signal aborts when the grid unmounts or saveTimeoutMs runs out. Pass it to fetch.

saveTimeoutMs (off by default) refuses a save that has not settled in time. The grid reverts the rows and sets reason: "timeout" on each rejection. Leave it off when your server can apply a save late.

Save rows from a server source

With useDataGridServerRows, pass onSave to the hook. gridProps.onSave runs your handler and fetches again by the refreshAfterSave policy. A refresh keeps a row with a pending save or an open edit.

Pass save from the sample above as onSave. The hook fetches again once the saves settle:

const server = useDataGridServerRows<Order>({
  mode: "scroll",
  fetchRows,
  onSave: save,
});

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

refreshAfterSave takes one of these values:

ValueRefresh
"settled" (default)Once, after every save in flight has settled, or after 10 seconds when at least one save has settled by then.
"each"After saves settle, without waiting for the saves in flight. Saves that settle in the same task share one refresh.
falseNever. Call server.refresh() yourself.
a functionWhen it returns true, at the times "settled" refreshes. It receives the saved, rejected, and failed counts, the changes of those saves (at most 100), and pending, the number of saves still in flight.

Beyond 10 blocks of rendered rows plus overscan, a sequential source skips the refresh: call server.refresh().

A refresh needs at least one onSave promise that resolved, with nothing or with { rejected }.

Swap a client id for the server id

A row that the user creates carries a client id. After the server saves it, call actions.replaceRowId(oldId, row) with the server row. The second argument of onSave carries the actions. This handler sends inserts only. Send the other operations as in Revert or refetch after a save:

"use client";

import { DataGrid, type DataChange, type SaveContext } from "@/components/data-grid/data-grid";
import { columns, type Order } from "./orders";

export function OrdersGrid({ rows }: { rows: Order[] }) {
  async function save(change: DataChange<Order>, ctx: SaveContext) {
    for (const op of change.ops) {
      if (op.type !== "insert") continue;
      const response = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(op.row),
        signal: ctx.signal,
      });
      if (!response.ok) throw new Error(`Save failed: ${response.status}`);
      ctx.actions.replaceRowId(op.rowId, await response.json());
    }
  }

  return (
    <DataGrid defaultData={rows} columns={columns} onSave={save} />
  );
}

One onDataChange call fires, with source: "id-swap", and history does not record it. The state keyed by the row id follows the new id. That covers the open edit, the cell errors, the checked rows, the save status, the saves in flight, and the undo steps. Flashes of the row end, and validateRow runs again.

After a batch create, call actions.replaceRowIds([{ oldId, row }]) to swap many rows in one write. A readOnly grid skips the swap.

Server mode

onSave works the same on a local array, a page, and scroll mode. Your server applies each operation by rowId.

On this page