gridcn2.0.0
Save to a server

Revert or refetch after a save

Load rows into your own state, turn grid changes into API calls, then roll a failed save back or refetch the rows after the server confirms.

Send every edit to your API from onSave. The grid shows the edit at once. If the request fails, the grid reverts it. If the server recomputes values, refetch the rows after the save.

The samples keep the rows in your own state, and onDataChange writes each change into it. The samples take Order and columns from orders.ts. The DataChange shape is on Data change events.

Load the rows

Fetch once, hold the rows in state, and pass the setter to onDataChange:

"use client";

import { useEffect, useState } from "react";
import { DataGrid, type DataChange } from "@/components/data-grid/data-grid";
import { columns, type Order } from "./orders";
import { opsToRequests } from "./ops-to-requests";

export function OrdersGrid() {
  const [data, setData] = useState<readonly Order[]>([]);

  useEffect(() => {
    let cancelled = false;
    fetch("/api/orders")
      .then((response) => response.json())
      .then((rows: Order[]) => {
        if (!cancelled) setData(rows);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  async function save(change: DataChange<Order>) {
    await Promise.all(opsToRequests(change.ops));
  }

  return (
    <DataGrid
      data={data}
      columns={columns}
      getRowId={(row) => row.id}
      onDataChange={setData}
      onSave={save}
    />
  );
}

Translate operations into API calls

Put opsToRequests in ops-to-requests.ts. change.ops holds one operation per touched row. Switch on op.type to pick the request. Sorting or filtering changes a view index, so key each request by rowId:

import type { DataOp } from "@/components/data-grid/data-grid";
import type { Order } from "./orders";

async function send(method: string, url: string, body?: unknown) {
  const response = await fetch(url, {
    method,
    headers: { "Content-Type": "application/json" },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
}

export function opsToRequests(ops: DataOp<Order>[]) {
  const requests = ops.flatMap((op) => {
    switch (op.type) {
      case "update": {
        const patch = op.cells
          ? Object.fromEntries(op.cells.map((c) => [c.columnId, c.value]))
          : op.row;
        return [send("PATCH", `/api/orders/${op.rowId}`, patch)];
      }
      case "insert":
        return [send("POST", "/api/orders", op.row)];
      case "delete":
        return [send("DELETE", `/api/orders/${op.rowId}`)];
      case "move":
        return [];
    }
  });
  const moves = ops.flatMap((op) =>
    op.type === "move"
      ? [
          {
            rowId: op.rowId,
            to: op.to,
            afterRowId: op.afterRowId,
            beforeRowId: op.beforeRowId,
          },
        ]
      : [],
  );
  if (moves.length > 0) {
    requests.push(send("POST", "/api/orders/reorder", moves));
  }
  return requests;
}

A cell edit, paste, or fill carries op.cells. A whole-row update has no cells. Send all moves of one change in one request. Each to is the final index of the row after the whole batch, counted in data.

In pages mode, data is the current page, so to counts from the first row of the page. In scroll mode, a move needs every row loaded, so to counts in the full data. The server removes every moved row, then inserts the rows in ascending to order. Moves applied one at a time end in the wrong order.

Each move also carries afterRowId and beforeRowId, the ids of the rows around it after the batch. A server that holds more rows than the grid places the row next to those ids. A move from undo or redo carries beforeRowId and afterRowId like any other move.

Strategy A: roll back on failure

Let onSave return the promise of the requests, as in Load the rows. If the promise rejects, the grid reverts the whole change and calls onSaveRejected. Add that prop to tell the user:

onSaveRejected={() => alert("Could not save. The change was reverted.")}

The revert is one more onDataChange call with source: "rollback". onSave never receives that call, so a revert does not go back to the server. A cell reverts only while it still holds the refused value, so a newer edit of the same cell stays.

If one request of a batch fails and the others succeed, the whole batch reverts. To revert only the refused rows, see Handle refused saves.

Strategy B: refetch after the save

If the server recomputes values, for example a price that triggers a discount, pick this strategy. Replace data with a fresh fetch after the write succeeds:

import { useState } from "react";
import { DataGrid, type DataChange } from "@/components/data-grid/data-grid";
import { columns, type Order } from "./orders";
import { opsToRequests } from "./ops-to-requests";

export function RefetchingGrid({ rows }: { rows: Order[] }) {
  const [data, setData] = useState<readonly Order[]>(rows);

  async function save(change: DataChange<Order>) {
    await Promise.all(opsToRequests(change.ops));
    const response = await fetch("/api/orders");
    setData(await response.json());
  }

  return (
    <DataGrid
      data={data}
      columns={columns}
      getRowId={(row) => row.id}
      onDataChange={setData}
      onSave={save}
    />
  );
}

The refetch replaces every row. An edit that the user made during the request shows the server value until its own save refetches. To keep such rows, pass onSave to useDataGridServerRows. The hook refreshes after the saves settle and keeps a row with an open edit or a save in flight.

Show the server error on the cell

A server often rejects one field, for example with a 422. Paint that rejection on the cell and keep the row. See Show errors on cells.

Server grids and controlled state

With useDataGridServerRows, pass onSave and refreshAfterSave to the hook. The hook fetches again after the saves settle, so Strategy B needs no code of its own. Save edits lists the policies. If your app owns the sort, filter, or search, pass them to the hook as spec with onSpecChange. The refresh sends the current spec. The refetched rows keep the order of the view.

Result

An edit appears in the grid before the server answers. A failed save reverts the edit. A saved edit stays, or the refetch replaces it with the server values.

On this page