Skip to content

Save changes in a batch ​

When a user edits a cell or adds or removes a row, the grid records the change. When the user clicks Save, you send everything at once. In the demo, rename a row to "Liam Carter" and save. The mock server rejects a name that already exists, and it gives each new row a new ID.

Live demo — drawn by the real renderer

Choose a save mode ​

Set the saveMode option.

ModeTracks changesBehavior
'batch' (default)YesCollects changes and sends them when you call save()
'immediate'YesSaves each time an edit is confirmed. Requires the saveHandler option
'none'NoRecords nothing. getChanges() returns [] and save() throws
ts
const options = {
  columns,
  rows,
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: async (changes) => {
    await fetch('/api/staff', { method: 'POST', body: JSON.stringify(changes) });
  },
};

You can change the mode later with setOptions({ saveMode }). While changes are pending, switching to 'none' or 'immediate' is refused with invalid-option, and nothing changes. Save or call rollbackChanges() first.

Read the pending changes ​

ts
api.hasChanges(); // true
api.getChanges();
ts
[
  {
    key: 2,
    state: 'modified',
    row: { id: 2, name: 'Emma Wilson', department: 'Product', salary: 78000 },
    cells: [{ columnId: 'department', oldValue: 'Design', newValue: 'Product' }],
  },
  {
    key: 100,
    state: 'added',
    row: { id: 100, name: 'Ethan Hayes', department: 'Design', salary: 74000 },
  },
  {
    key: 5,
    state: 'removed',
    row: { id: 5, name: 'Ava Turner', department: 'Engineering', salary: 76000 },
  },
];
  • A modified entry lists only the cells that changed. oldValue is the value from the baseline.
  • If a user sets a cell back to its original value, that cell leaves the list. When no changed cell remains in a row, the row leaves too. Removing a row you just added leaves no trace.
  • Rows hidden by a filter or sort are included.
  • row is the object the grid holds, not a copy. Read it; do not modify it.

changesCountChanged fires whenever the counts change. Use it to enable the Save button.

ts
api.on('changesCountChanged', ({ count, added, modified, removed, saving }) => {
  saveButton.disabled = count === 0 || saving;
  status.textContent = `${added} added · ${modified} modified · ${removed} removed`;
});

Ask and revert per row ​

Since 1.3.5

The methods below and the events batchStarted and batchEnded are available from 1.3.5. Without them everything behaves as before. With saveMode: 'none' all of them throw invalid-option.

getChanges() returns the whole list, which is heavy for asking about one row. You can ask about one row or one cell directly.

ts
api.getRowState(7); // 'added' | 'modified' | 'removed' | null (unchanged or unknown key)
api.isCellChanged(7, 'price'); // true if the cell of a modified row differs from its original
api.getRowsWithState(); // [{ key, row, state }] the rows in the store, in store order

api.revertRows([7, 9]); // revert only these rows; returns the number of rows reverted
api.revertCells([{ rowKey: 7, columnId: 'price' }]); // only this cell to its original; returns the cell count
api.acceptRows([7]); // keep the current values as the new originals without saving (leaves the change list)
MethodWhat it does
revertRows(keys)Modified: original values; added: removed; removed: re-inserted at its place. Unknown and unchanged keys are skipped
revertCells(cells)Only cells of modified rows go back; a row with no changed cell left becomes unchanged
acceptRows(keys)Removed from the change log. The save handler is not called and no changesCommitted is emitted; changesCountChanged is
  • revertRows writes the way rollbackChanges does (same write path) and adds no undo step.
  • A removed row is not in the store, so getRowsWithState does not list it. Read removed rows with getChanges().
  • batchStarted fires when the first change appears and batchEnded { reason, count } when the list becomes empty again. reason is commit, rollback, accept or revert, and count is the number of rows that were in the list. Emptying it by editing a cell back or by reverting some rows is also revert; replacing all rows with setRows is rollback. The order is changesCountChanged, batchEnded, then changesCommitted or changesRolledBack.

Sync the changes of two grids ​

ts
const report = other.applyChanges(api.getChanges()); // { applied, skipped }

Pass the result of getChanges() to another grid with the same columns. Added rows are added, modified rows are updated cell by cell from the new values in cells, removed rows are removed. An added row whose key exists, and a modified or removed row whose key is unknown, are skipped and counted in skipped. The writes are ordinary tracked changes in this grid, and the updates and removals form one undo step (additions are not undoable). Rows that a hook such as beforeRemoveRows blocks count as skipped.

Send changes to the server ​

Pass a handler to save(), or set saveHandler in the options. The handler receives the change list and posts it.

ts
const report = await api.save(async (changes, { signal }) => {
  const response = await fetch('/api/staff/bulk', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(changes),
    signal,
  });
  if (!response.ok) throw new Error(`Save failed (${response.status})`);
});

if (report.status === 'saved') toast('Saved.');

If the handler returns nothing, the grid treats every row as saved and confirms the changes. If it throws or rejects, the changes stay and saveFailed fires.

report.status is one of these:

StatusMeaning
savedEverything saved. committed is the number of confirmed rows
partialSome rows saved. failed is the number of rows that failed
failedThe handler threw. error holds the value, and the changes are unchanged
invalidValidation failed before sending, so the handler was not called. errors lists the cells
emptyNothing to save, so the handler was not called
staleThe grid was destroyed or the changes were reset while waiting, so the response was dropped

Report rows that failed ​

To report success and failure per row, return an object.

ts
await api.save(async (changes) => {
  const result = await postBulk(changes); // { savedIds: number[], errors: { id: number, reason: string }[] }
  return {
    ok: result.savedIds,
    failed: result.errors.map((e) => ({ key: e.id, message: e.reason })),
  };
});
  • A key in neither ok nor failed counts as saved. You do not have to list every success.
  • A key in failed is a failure even if ok also lists it.
  • A failed row stays in the change list, shows an error mark, and carries the message as its title. The mark clears when the user edits the row again, rolls back, or saves it successfully.
  • Any entry in failed fires saveFailed. status is partial when some rows saved and failed when none did.

Apply values the server decides ​

When the server assigns a value, such as the ID of a new row, return { key, row } in ok. The grid replaces the row.

ts
await api.save(async (changes) => {
  const saved = await postBulk(changes); // [{ clientId: -1, row: { id: 1042, ... } }]
  return { ok: saved.map((s) => ({ key: s.clientId, row: s.row })) };
});

If the returned row has a different key, the key changes in place, and the selection and focus follow it. selectionChanged may fire an extra time while this happens.

Validate before saving ​

Before sending, save() checks every changed row against the validation rules of its columns, hidden rows included. If any cell fails, the handler is not called, and you get status: 'invalid' with the errors. Focus moves to the first failing cell. If a cell is being edited, the grid confirms it first and returns that error if it fails.

Validation in save() includes validation.unique. To check the current data without saving, use api.validateRows({ changedOnly: true }) (Validate input).

Follow the rules while a save runs ​

  • Calling save() again while one is running does not send a second request. It returns the result of the running one, so a double click is safe.
  • Edits made during a save are not lost. A cell that still matches the value you sent is confirmed. A cell the user changed again stays pending for the next save.
  • In immediate mode, changes that arrive during a save go out in one more save afterward.
  • If rollbackChanges(), commitChanges() or setRows resets the baseline, the running save's response is dropped and the status is stale. Destroying the grid aborts the handler's signal.

Roll back or confirm ​

ts
api.rollbackChanges(); // restores edited cells and removed rows, drops added rows, in one step
api.commitChanges(); // takes the current data as the new baseline and clears the log

rollbackChanges() cancels an open edit first. commitChanges() does not talk to a server. It only resets the grid's baseline. save() is what sends data.

beginBulkEdit() and endBulkEdit() group writes into one undo step, independent of saving (Cell editing). The change list still collects each written cell.

Save points versus rollback ​

ItemrollbackChanges, revertRowsrestoreSavePoint
Where it goes back toThe last confirmed stateA point you made with createSavePoint
What it coversEdited cells, added and removed rows (changes)A copy of all rows
Change tracking, historyOnly what was reverted is cleanedCleared completely (as if freshly loaded)
How many pointsOne (the last confirmation)Up to 20

Use save points for try-and-roll-back screens and change rollback for edits before saving. See Go back to a save point.

Warn before the user leaves ​

The grid adds no global listeners. To warn on page unload, check hasChanges() in your app.

ts
window.addEventListener('beforeunload', (event) => {
  if (api.hasChanges()) event.preventDefault();
});

For in-app navigation, run the same check in your router's leave guard.

Spot change marks ​

The renderer adds these classes, and the theme styles them. They do not rely on color alone: they add a corner mark, a left bar or an inner border.

ClassTargetLook
mxg-cell-dirtyCellYellow background, mark in the top-right corner
mxg-cell-invalidCellRed background, inner border
mxg-row-addedRowGreen background, bar on the left
mxg-row-failedRowRed background, bar on the left. Message in title

Change the colors with --mxg-bg-dirty, --mxg-bg-added, --mxg-mark-dirty and --mxg-mark-added (Theme).

Pitfalls ​

  • With saveMode: 'none', save(), commitChanges() and rollbackChanges() throw invalid-option. getChanges() returns [] and hasChanges() returns false.
  • saveMode: 'immediate' without a saveHandler throws invalid-option when the options are applied.
  • setRows treats the new data as the baseline and clears the change log. Pending changes are discarded, so check hasChanges() first. The same happens when React or Vue state passes a whole new rows array.
  • Removing a row deletes it from the data. It does not stay on screen with a strikethrough. Use rollbackChanges() to bring it back.
  • The row in each change is the grid's own object. Use it to build the request, and do not keep or mutate it.