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.
Choose a save mode
Set the saveMode option.
| Mode | Tracks changes | Behavior |
|---|---|---|
'batch' (default) | Yes | Collects changes and sends them when you call save() |
'immediate' | Yes | Saves each time an edit is confirmed. Requires the saveHandler option |
'none' | No | Records nothing. getChanges() returns [] and save() throws |
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
api.hasChanges(); // true
api.getChanges();[
{
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
modifiedentry lists only the cells that changed.oldValueis 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.
rowis 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.
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.
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)| Method | What 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 |
revertRowswrites the wayrollbackChangesdoes (same write path) and adds no undo step.- A removed row is not in the store, so
getRowsWithStatedoes not list it. Read removed rows withgetChanges(). batchStartedfires when the first change appears andbatchEnded { reason, count }when the list becomes empty again.reasoniscommit,rollback,acceptorrevert, andcountis the number of rows that were in the list. Emptying it by editing a cell back or by reverting some rows is alsorevert; replacing all rows withsetRowsisrollback. The order ischangesCountChanged,batchEnded, thenchangesCommittedorchangesRolledBack.
Sync the changes of two grids
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.
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:
| Status | Meaning |
|---|---|
saved | Everything saved. committed is the number of confirmed rows |
partial | Some rows saved. failed is the number of rows that failed |
failed | The handler threw. error holds the value, and the changes are unchanged |
invalid | Validation failed before sending, so the handler was not called. errors lists the cells |
empty | Nothing to save, so the handler was not called |
stale | The 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.
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
oknorfailedcounts as saved. You do not have to list every success. - A key in
failedis a failure even ifokalso 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
failedfiressaveFailed.statusispartialwhen some rows saved andfailedwhen 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.
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
immediatemode, changes that arrive during a save go out in one more save afterward. - If
rollbackChanges(),commitChanges()orsetRowsresets the baseline, the running save's response is dropped and the status isstale. Destroying the grid aborts the handler'ssignal.
Roll back or confirm
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 logrollbackChanges() 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
| Item | rollbackChanges, revertRows | restoreSavePoint |
|---|---|---|
| Where it goes back to | The last confirmed state | A point you made with createSavePoint |
| What it covers | Edited cells, added and removed rows (changes) | A copy of all rows |
| Change tracking, history | Only what was reverted is cleaned | Cleared completely (as if freshly loaded) |
| How many points | One (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.
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.
| Class | Target | Look |
|---|---|---|
mxg-cell-dirty | Cell | Yellow background, mark in the top-right corner |
mxg-cell-invalid | Cell | Red background, inner border |
mxg-row-added | Row | Green background, bar on the left |
mxg-row-failed | Row | Red 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()androllbackChanges()throwinvalid-option.getChanges()returns[]andhasChanges()returnsfalse. saveMode: 'immediate'without asaveHandlerthrowsinvalid-optionwhen the options are applied.setRowstreats the new data as the baseline and clears the change log. Pending changes are discarded, so checkhasChanges()first. The same happens when React or Vue state passes a whole newrowsarray.- Removing a row deletes it from the data. It does not stay on screen with a strikethrough. Use
rollbackChanges()to bring it back. - The
rowin each change is the grid's own object. Use it to build the request, and do not keep or mutate it.