SpreadsheetGrid
Guides

Change tracking

Mark edited cells as unsaved with trackChanges, take out what to send with getChanges, and clear the marks with markChangesSaved after saving

With trackChanges, cells edited in the grid get an "unsaved" mark (since 1.8.0). The grid remembers which cells were edited, so when saving, take out only the edited rows and columns with the handle's getChanges(), send them to the server, and clear the marks with markChangesSaved() once they arrive. Cells typed back to their original value lose the mark automatically.

To compare a previous version of the rows (last month's table, the server's values and so on) with the current rows and show the differences in color, use the diff view with trackChanges={{ baseline }} (since 1.13.0; it compares the two sets of rows you pass, whether or not they were edited in the grid).

Demo (price list > edit and save)

Rows 12 of 12Columns 7 of 7Sort: —
#
1
2
3
4
5
6
7
8
9
10
11
12
Rows 12 of 12Columns 7 of 7
Cell —Range —0 cells / 0 rows0 columns

(Edit a cell and press Save; what was sent shows up here)

  • Edit a cell, and a triangle appears at its top left, a dot at the top left of the row number, and "Unsaved: 1 row, 1 cell" in the bar below. Hover a cell with a triangle to see the value before the change.
  • Type an edited cell back to its original value, and the mark goes away. The same happens when you revert with Ctrl+Z (⌘Z on Mac).
  • "Save" sends only the edited rows to a fake server (it waits 0.7 seconds) and clears the marks when they arrive. Cells you edit while waiting stay unsaved. Turn on "Make saving fail", and the marks stay.
  • "Update stock from the server" replaces rows with the server's values (the approach in "Replacing rows from outside" below). Rows whose stock you didn't edit get the arrived values; stock you edited keeps your value and its mark.
  • Right-click an unsaved cell for "Revert this cell", plus "Revert this row" if the row has other unsaved cells (right-clicking a row number shows the row item). Select a range and right-click for "Revert the selection" too. Reverts can be undone with Ctrl+Z as well.

Usage

import { useRef, useState } from 'react';
import { SpreadsheetGrid, type SpreadsheetGridHandle } from '@ishibashi0112/spreadsheet-grid';

const gridRef = useRef<SpreadsheetGridHandle<Product>>(null);
const [unsavedRows, setUnsavedRows] = useState(0);

const save = async () => {
  const grid = gridRef.current;
  if (!grid || grid.getInvalidCells().length > 0) return; // validate first
  const changes = grid.getChanges();
  if (changes.rowCount === 0) return;
  await api.saveProducts(
    // per row, the keys of the edited columns and the current row
    changes.rows.map(({ rowKey, columnKeys, row }) => ({ id: rowKey, columnKeys, row })),
  );
  // mark only what was sent as saved (cells edited while waiting stay unsaved)
  grid.markChangesSaved(changes);
};

<>
  <button type="button" disabled={unsavedRows === 0} onClick={() => void save()}>
    Save
  </button>
  <SpreadsheetGrid
    ref={gridRef}
    rows={rows}
    onRowsChange={setRows}
    rowKeyGetter={(row) => row.id} // required, since changes are tracked by row key
    columns={columns}
    trackChanges
    onChangesChange={({ rowCount }) => setUnsavedRows(rowCount)}
  />
</>;

trackChanges works when rows are passed with rows + onRowsChange (clientSide) and there is a rowKeyGetter. When something is missing, it does nothing and warns in development.

React onlyFor large tables (100,000 rows or more), define rowKeyGetter outside the component or wrap it in useCallback. If you keep the count from onChangesChange in the parent's state, the parent re-renders on every edit that changes the count, and with an inline rowKeyGetter the grid rebuilds the row order for all rows (each commit takes about 1.5 times as long with 1 million rows; Large data).

What to send for saving (getChanges)

getChanges() returns { rows, rowCount, cellCount }. rows holds only rows with unsaved cells, in the current order of rows.

FieldContents
rowKeyThe row key (the rowKeyGetter value)
rowThe current row (the very row in rows; don't mutate it)
originalThe row with only the unsaved columns set back to their saved values (other columns are current values; for checking on the server "is it the same as before the change")
columnKeysKeys of the unsaved columns (in columns order)
  • Your app decides the shape to send. To send whole rows, use row; to send only edited columns, pick them from row with columnKeys.
  • Calling it inside onRowsChange includes that change. The list is made fresh on every call, so modifying the array doesn't affect the grid (row is the very row in rows).
  • Calling it after the grid is unmounted (a confirmation before leaving the page, for example) returns the list as of unmounting.
  • Validation is separate. If you don't want to send marked cells, check with getInvalidCells() first (Validation). getInvalidCells() includes unedited rows too, so for data that already has values failing validation, narrow it to the edited cells.
const changes = grid.getChanges();
const changed = new Set(changes.rows.flatMap((change) => change.columnKeys.map((key) => `${String(change.rowKey)}:${key}`)));
const invalid = grid.getInvalidCells().filter((cell) => changed.has(`${String(cell.rowKey)}:${cell.columnKey}`));

Marking as saved (markChangesSaved)

CallWhat becomes saved
markChangesSaved()Everything
markChangesSaved([rowKey, ...])Those rows
markChangesSaved(changes)Only the values in the getChanges() result you sent
markChangesSaved({ rows: [...] })Only the values of the rows in the list (a filtered changes.rows; counts and original aren't used)
  • The grid stays usable while waiting for a save. If the same cell is typed again after sending, markChangesSaved(changes) makes the sent value the saved value, and the retyped cell stays unsaved. Marking everything as saved with markChangesSaved() (no argument) counts that retyping as saved too, so we recommend passing what you sent.
  • Cells reverted to their original value with Ctrl+Z between sending and the save finishing also stay unsaved, because the current value differs from what was sent (the server now has the sent value).
  • When saving fails, just don't call anything, and the marks stay.
  • When only some rows were saved, pass the sent list narrowed to those rows (markChangesSaved([rowKey, ...]) would also mark cells edited in those rows while waiting as saved).
const result = await api.saveProducts(payload); // e.g. { savedIds: [...] }
const saved = new Set(result.savedIds);
grid.markChangesSaved({ rows: changes.rows.filter((change) => saved.has(change.rowKey)) });
  • It doesn't change values, so it isn't recorded in the undo history. If you revert with Ctrl+Z after marking as saved, the reverted value differs from the saved value, so it becomes unsaved again (save again, or type it back).
  • When the server corrects values and returns them (trimming spaces, assigning numbers and so on), call markChangesSaved(changes) first, then pass the returned rows with applyRows(returnedRows, { asSaved: true }). Cells whose sent value was marked as saved get the returned value, and cells retyped while waiting keep the retyped value and stay unsaved (passing with asSaved alone leaves cells whose sent and returned values differ at the sent value and unsaved).

What is tracked

  • Changes the grid makes are tracked: cell edits, paste, clearing with Delete, the fill handle, checkboxes, setValue in renderCell, undo / redo, and the handle's applyRows.
  • When you edit rows in your own form outside the grid (a detail row card, side panel or dialog), pass them through the handle's applyRows(next), not the parent's setRows. Changes passed with setRows are outside replacements; they aren't counted as unsaved and aren't in getChanges() (they'd be missed when saving).
  • The value before a cell first changes is kept as the "saved value", and cells whose current value differs are unsaved. Values are compared with Object.is (typing back to the saved value clears the mark. Object values with the same contents are different values if they're different objects. Since 1.13.0, Dates are compared by time).
  • trackChanges (true) doesn't track rows being added, removed or reordered. Rows that were only added aren't counted as unsaved. If you edit a cell of a row after adding it, that cell becomes unsaved (its saved value is the value when added). Apps that also send added and removed rows use trackChanges={{ rows: true }} below (since 1.10.0).
  • Computed columns (only getValue, no setValue) aren't counted. Columns with both getValue and setValue are compared by the getValue value.
  • Only column values are compared. Fields not in any column aren't tracked. Read-only columns (editable: false / readOnly) are compared too, so columns filled by the select editor's fillRow become unsaved as well (Searchable select editor). Columns filled together by fillRow aren't reverted by "Revert this cell" on the select cell ("Revert this row" reverts them. To keep cell reverts aligned too, write setValue on the select column and write the related columns together from the chosen value).
  • Hidden columns are compared too (the marks are kept while the column is hidden). Columns removed from the columns array also keep counting their unsaved values (the row number dot, counts and getChanges() include them; bring the column back and the cell marks come back).
  • When the parent doesn't render the rows passed in onRowsChange (it validates the input and rejects it, for example), that change isn't counted. Rendering a copy of the received rows or a version with corrected values is counted.

Replacing rows from outside

When new values arrive from the server, we recommend passing them with applyRows(next, { asSaved: true }) rather than the parent's setRows.

Making arrived values the saved values (asSaved of applyRows)

Pass the rows of a save response, someone else's update or refetched rows (rows arriving through Next.js's router.refresh() and so on), and the values you pass become the server's current values = the saved values.

const receiveFromServer = (serverRows: Product[]) => {
  gridRef.current?.applyRows(serverRows, { asSaved: true });
};
  • Cells you didn't edit get the passed values (they don't become unsaved).
  • Cells being edited (unsaved) keep their current value, and the passed value becomes their saved value. The description becomes "Unsaved (was 999)", and reverting goes back to the passed value. If the current value equals the passed value, the mark goes away.
  • It isn't recorded in the undo history, and the current history isn't cleared (the same as undoable: false). Ctrl+Z reverts only changes made in the grid.
  • Rows arriving while waiting for a save (after sending, before the response) can be passed the same way. Sent cells stay unsaved if the arrived value differs from the sent value, and become saved when you call markChangesSaved(changes) on the save response.
  • If only some rows came back (only the saved rows), you can lay them over the current rows and pass that. Rows you pass that are the same as the current rows (===; rows that didn't come back) aren't treated as server values, so cells edited while waiting and rows added or removed stay unsaved (since 1.10.0. Up to 1.9, passing them laid over also marked cells edited while waiting as saved).
const merge = (returned: Product[]) => {
  const byId = new Map(returned.map((row) => [row.id, row]));
  gridRef.current?.applyRows((prev) => prev.map((row) => byId.get(row.id) ?? row), { asSaved: true });
};

Replacing with setRows

Replacing rows with the parent's setRows doesn't change the saved values.

  • In unsaved rows, columns you didn't edit show the outside values as they are (they don't become unsaved).
  • Edited columns keep being compared with the saved values. The values of the replaced rows are shown as they are, so if outside values overwrite edited values, the unsaved mark appears when the outside value differs from the saved value, and goes away when it's the same (your edited value isn't kept).
  • Every replacement clears the undo history (the row array is a different one).
  • applyRows(next, { undoable: false }) (without asSaved) is also treated as an outside replacement (the history stays).
  • Removing rows from outside also drops their records (even if a row with the same key arrives again, the old records don't come back).
  • The saved values don't change, so reverting an edited cell goes back to the value before the edit (not the server's current value). To go back to the server's value, pass it with asSaved.
  • For conflict checks when saving, you can use original (the row with the saved values). If the server's current value differs from original, someone else changed it first.

Reverting (revertChanges and the context menu)

  • The handle's revertChanges() sets all unsaved cells, and revertChanges([rowKey, ...]) those rows' unsaved cells, back to their saved values. It calls onRowsChange once and records it in the undo history as one change (Ctrl+Z takes you back to before the revert).
  • The context menu's params.revertItems holds "Revert this cell", "Revert this row" and "Revert the selection" (only when the target has unsaved cells; [] otherwise and while readOnly). Your app builds the menu, so put them in the array you return to use them. The items' ids are ssg-revert-cell / ssg-revert-row / ssg-revert-selection (useful, for example, to show your own items only for unsaved cells).
<SpreadsheetGrid
  // ...
  trackChanges
  enableContextMenu
  getContextMenuItems={(params) => [
    ...(params.revertItems ?? []), // "Revert …" at the top
    ...(params.revertItems?.length ? [{ kind: 'separator' as const, id: 'sep-revert' }] : []),
    // ...your app's items
  ]}
/>
  • The cell item is included when the right-clicked cell is unsaved.
  • The row item is included when the row has unsaved cells other than the right-clicked cell (if the row's only unsaved cell is that one, it would be the same as the cell item, so it isn't shown). When a row number is right-clicked, it's included if the row has unsaved cells.
  • The selection item is included when the right-clicked cell (the row, for a row number) is inside the selection and the range has unsaved cells other than the right-clicked cell (or row). Right-clicking a row number includes it too if a cell range over that row is selected. Only cells inside the range are reverted (for a cell range, only the range's columns). If the range's unsaved cells are the same as the row item's, it isn't shown.

Look and texts of the marks

MarkWhereHow to change
Triangle at the top left (8px)Unsaved cells (child element .ssg-unsaved-mark, .ssg-body-cell--unsaved on the cell)Color with the token --ssg-unsaved-indicator (default is the accent color)
Dot at the top left of the row numberRow numbers of rows with unsaved cells (.ssg-row-header-cell--unsaved, .ssg-body-row--unsaved on the row). When a closed parent in tree data contains unsaved rows, also on that parent's row number (without .ssg-body-row--unsaved on the row. Since 1.9.0)Same token
"Unsaved: 2 rows, 3 cells"The default bottom bar (.ssg-bar-chip--unsaved; hidden at 0)Text is unsavedChanges in localeText
Vertical line left of the row numberRow numbers of rows added in the grid with trackChanges={{ rows: true }} (.ssg-row-header-cell--added, .ssg-body-row--added on the row. Since 1.10.0)Same token
/* make the unsaved marks orange */
.ssg-root {
  --ssg-unsaved-indicator: #ea580c;
}
  • The tooltip and spoken description of a cell with a triangle is "Unsaved (was 120)" (the previous value is the text after the column's valueFormatter; empty is "(empty)", and checkboxes are "checked / unchecked"). When it overlaps a validation error or note (cellNote), the tooltip lists them in the order "error → note → unsaved", and the mark is at the top left rather than the top right where the note's is, so they don't overlap.
  • The spoken description of the row number is "Has unsaved changes". For a closed parent in tree data, it's "Has unsaved changes inside" (unsavedInClosedTreeRow).
  • In Windows high contrast (forced-colors), the triangles and dots are shown in the system's highlight color.
  • The texts are unsavedChanges / unsavedCell / unsavedEmptyValue / unsavedChecked / unsavedUnchecked / unsavedRow / unsavedInClosedTreeRow / revertCellChanges / revertRowChanges / revertSelectionChanges in localeText, and for added and removed rows unsavedAddedRows / unsavedRemovedRows / unsavedRowChanges / unsavedSeparator / unsavedAddedRow (they're in the English table localeTextEn too; English and text).

In your own bottom bar (renderBottomBar), show the counts with slotContext.unsavedChanges ({ rowCount, cellCount }; null when trackChanges isn't in effect).

Tracking added and removed rows too

With trackChanges={{ rows: true }}, rows added and removed in the grid are tracked too (since 1.10.0). Use it to save rows added with the entry row. Tables with trackChanges (true) behave as before.

<SpreadsheetGrid
  ref={gridRef}
  rows={rows}
  onRowsChange={setRows}
  rowKeyGetter={(row) => row.id}
  createRow={() => ({ id: crypto.randomUUID(), name: '', qty: null })}
  newRow
  columns={columns}
  trackChanges={{ rows: true }}
/>;

const save = async () => {
  const grid = gridRef.current;
  if (!grid) return;
  const changes = grid.getChanges(); // { rows, rowCount, cellCount, added, removed, addedCount, removedCount }
  await api.save({
    insert: changes.added?.map(({ row }) => row) ?? [],
    update: changes.rows.map(({ rowKey, row, columnKeys }) => ({ id: rowKey, columnKeys, row })),
    delete: changes.removed?.map(({ rowKey }) => rowKey) ?? [],
  });
  grid.markChangesSaved(changes);
};
  • What is counted: rows added and removed by changes the grid makes. Rows added in the entry row, rows added by a paste that spills past the end, rows added and removed with the handle's applyRows, and undo and redo of those. Rows that increase or decrease when rows is replaced from outside aren't counted (so asynchronously loaded rows don't all become "added"). When you build a button that deletes rows, delete with applyRows, not setRows.
  • Added rows: they appear once in getChanges().added (an array of { rowKey, row } in rows order) and aren't counted as unsaved cells (cells edited after adding get no triangle, and row holds the current values). A vertical line appears left of the row number, and the spoken description is "Added row (unsaved)". Removing an added row means nothing happened.
  • Removed rows: they appear in getChanges().removed as the row with its saved values before removal (unsaved cells set back to their saved values). They aren't shown in the table. Undoing the removal takes them out of removed and brings back their cells' unsaved marks.
  • Counts: onChangesChange and slotContext.unsavedChanges include addedCount / removedCount, and the default bottom bar shows "Unsaved: 2 rows, 3 cells, 1 row added, 1 row removed" (with no cells, "Unsaved: 1 row added"). Drafts in the entry row aren't counted (if your save button is disabled by the count, include whether there is a draft with the entry row's onDraftChange).
  • Marking as saved: markChangesSaved(changes) also marks the sent added / removed as saved (columns of an added row edited after sending remain as unsaved cells whose saved value is the sent value). markChangesSaved() marks everything, and markChangesSaved(rowKeys) those rows.
  • Reverting: revertChanges() removes added rows and puts removed rows back in their original place (after the row that was right before them) with their saved values (one change together with cell reverts; Ctrl+Z takes it back).
  • Making arrived values saved: with applyRows(serverRows, { asSaved: true }), added rows present in the arrived rows become saved, and added rows not present remain as not yet saved. Removed rows not in the arrived rows become saved, and removed rows present stay removed (rows added and removed while waiting for a save aren't lost). When you pass returned rows laid over the current rows (including rows identical to the current ones), removed rows not in the arrived rows also stay removed. If you removed an added row or undid a removal after sending, markChangesSaved(changes) turns that row into "removed" / "added" (to match the server).
  • getChanges() and the counts include added / removed / addedCount / removedCount only with { rows: true } (with true, it's the same { rows, rowCount, cellCount } as before).

serverSide and other features

  • It doesn't work with serverSide (dataSource). Cell edits are written back one by one through dataSource.updateRows, so saving / failure marks come from showSaveStatus (Server-side row model).
  • Change highlighting (highlightChanges) "flashes the moment a value changes" and is unrelated to the save state. Both can be used together.
  • During sorting, filtering, row grouping, column reordering and row drag, marks stay because tracking is by row and column keys. Changes in rows hidden by filters are in getChanges() too. Unsaved cells inside collapsed groups of row grouping (rowGroup) show no mark on the group row (they're in the counts and getChanges()).
  • Records are per grid. Unmounting the grid (moving pages, changing key) drops them, and a recreated grid starts from 0 (on unmount, onChangesChange is told 0, so the parent's count goes back to 0 too). Apps that come back with edited values kept in rows can render with the saved rows and then pass the kept rows with applyRows(kept) to bring the marks back (it adds one entry to the undo history). To check before leaving, call getChanges() before unmounting (the handle after unmounting also returns the list as of unmounting).

With /lite

With /lite, add the feature part changeTrackingFeature (it isn't in standardFeatures).

import { createSpreadsheetGrid, changeTrackingFeature, contextMenuFeature } from '@ishibashi0112/spreadsheet-grid/lite';

const Grid = createSpreadsheetGrid({
  features: { changeTracking: changeTrackingFeature, contextMenu: contextMenuFeature },
});

Adding trackChanges in a setup without it shows no marks, with one warning in development.

On this page