Handle refused saves
Answer from onSave with the rows the server refused, so the grid reverts only those rows and keeps the rest.
When a server refuses some rows of a change, return those rows from onSave. The grid reverts only the refused rows and keeps the rest.
Acknowledge each change
Send one request per operation, then return a rejection for each request that failed:
import {
DataGrid,
type DataChange,
type SaveAck,
type SaveRejection,
} from "@/components/data-grid/data-grid";
import { columns, type Order } from "./orders";
import { sendOp } from "./api";
async function onSave(change: DataChange<Order>): Promise<SaveAck<Order>> {
const results = await Promise.allSettled(change.ops.map(sendOp));
const rejected = results.flatMap((result, i): SaveRejection<Order>[] =>
result.status === "rejected"
? [{ rowId: change.ops[i]!.rowId, message: String(result.reason) }]
: [],
);
return { rejected };
}
export function OrdersGrid({ rows }: { rows: Order[] }) {
return (
<DataGrid
defaultData={rows}
columns={columns}
onSave={onSave}
onSaveRejected={({ rejected }) => alert(rejected[0]?.message)}
/>
);
}sendOp sends one request per operation, so each refusal maps to one row. To send move operations in one request, see Translate operations into API calls. Refuse every moved row when that request fails.
What the answer means
- A promise that resolves with nothing, or with
{ rejected: [] }, accepts the whole change. - A promise that rejects, or a handler that throws, refuses the whole change. Every row of the change reverts.
- An answer with more than 10,000 entries in
rejectedrefuses every row of the change, as a thrown error does, and warns once in development. - The grid skips an entry without a string
rowId. Arejectedthat is not an array accepts the whole change.
| Field | Meaning | Default |
|---|---|---|
rowId | The row the server refused. | none |
columnId | Refuses one cell of an update that lists cells. Any other operation is refused whole. | whole row |
message | Text for onSaveRejected, and the error text of the cells that keep marks. | none |
keep | Keeps the value and marks its cells with message. | false |
current | The row with the values the server holds. | none |
Put the server row in place
If you pass current, the revert writes that row in place of the old local row. A refused delete restores current without resolveSaveConflict. See Resolve a conflict. A refused insert removes the row and ignores current. A refused move reverts its position.
The grid ignores current when a newer write to the row exists. It also ignores current, and warns once in development, when getRowId(current) throws or differs from rowId.
Detect a conflict on the server
An update operation carries prev, the row before the edit, and its edited cells. If a stored field of an edited cell differs from prev, another user changed it. Refuse the row with current. Otherwise write only the edited cells. This handler refuses a cell outside EDITABLE and assumes that each editable column id names a row field:
import type {
DataOp,
SaveRejection,
} from "@/components/data-grid/data-grid";
import type { Order } from "./orders";
import { db } from "./db";
export async function POST(request: Request) {
const body: unknown = await request.json();
if (!Array.isArray(body)) {
return Response.json({ error: "Expected a list" }, { status: 400 });
}
const EDITABLE = new Set(["customer", "total"]);
const rejected: SaveRejection<Order>[] = [];
for (const op of body as DataOp<Order>[]) {
if (op?.type !== "update" || typeof op.rowId !== "string") continue;
const stored = await db.orders.find(op.rowId);
const before = op.prev as Record<string, unknown> | undefined;
const cells = op.cells ?? [];
if (
!stored ||
!before ||
cells.some((cell) => !EDITABLE.has(cell.columnId)) ||
cells.some((cell) => stored[cell.columnId] !== before[cell.columnId])
) {
rejected.push({ rowId: op.rowId, current: stored ?? undefined });
} else {
const entries = cells.map((c) => [c.columnId, c.value]);
const patch = Object.fromEntries(entries);
await db.orders.update(op.rowId, patch);
}
}
return Response.json({ rejected });
}Run the check and the write of each row in one transaction. The client sends change.ops to this route and returns the answer to the grid:
onSave={async (change) => {
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}`);
return response.json();
}}Resolve a conflict
When a refusal carries current, the revert takes the server row. To decide per row, pass resolveSaveConflict to the provider. It receives a SaveConflictContext, { rowId, mine, theirs, change, message, signal } for each refused row with a usable current. It does not run on a readOnly grid. mine is the row in the grid, and theirs is current. Return one of these:
| Return | Result |
|---|---|
"theirs" or nothing | The grid takes the server row. |
"mine" | The grid keeps its row. |
{ row } | The grid takes your merged row. |
In this demo, you pick one of the three answers:
Another user changed every row on the server. Edit a note and press Enter: the server refuses the save and sends its row. The choice below decides what the row becomes.
- No conflict yet.
"mine" and { row } commit one change with source: "merge" on top of the server row. onSave receives it, and history does not record it. A returned promise keeps the row saving until it settles. signal aborts when a newer write to the row starts or the grid unmounts.
This handler keeps the user's customer and takes the server's other fields: ({ mine, theirs }) => ({ row: { ...theirs, customer: mine.customer } }).
A change that took server content has DataChange.serverRowIds. useDataGridHistory drops older undo steps for those rows.
React to a refusal
- The revert is one
onDataChangecall withsource: "rollback". Therevertsfield names the refused change.onSavenever receives that call. onSaveRejected({ change, rejected, error, reverted })runs once per refused change, after the revert.revertedisfalsewhen every entry setkeep. If the promise resolved with{ rejected },errorisnull. Otherwiseerroris the rejection reason.- The row element carries
data-save-status="failed"after a refusal. See Save edits. - When the revert writes,
useDataGridHistoryremoves the whole refused entry from its undo stack, also for rows the server accepted. - The revert runs on a
readOnlygrid too. - If you replace the data before the answer, a refused update of a row that left reverts nothing.
- A throw in one callback goes to
reportErrorand does not stop the next.
Related
- Save edits: send each change from
onSave - Revert or refetch after a save: roll a failed save back, or fetch the rows again
- Show errors on cells: paint a server rejection on a cell
- Undo with server data: undo and redo with 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.
Show errors on cells
Paint a server rejection on the exact cell it names with setCellErrors, keep the value, and clear the error when the user fixes it.