Skip to content

Undo/Redo That Survives Sorting: Editing a Data Grid with an External Store ​

Three grid states show record A edited from 16 to 24 hours, moved to row two by sorting, and restored to 16 hours by undo.

Undo in a data grid should restore a record's previous value, not whatever happens to occupy its old position. That distinction becomes important as soon as the grid can sort rows and an external store can replace them. The solution is to record edits against stable record identities, replay them through the same write path as ordinary edits, and advance history only after that write succeeds.

We'll use a project allocation editor in React: an operator pastes hours into two rows, sorts the table, then reverses the paste without disturbing the sort. RevoGrid Pro 4.4.3 provides the edit and history integration; the application remains responsible for the data and its validation.

Why an index-based undo fails ​

Suppose the initial table contains:

Visible positionRecord IDProjectAllocated hoursCapacity
0designDesign1624
1engineeringEngineering2432

Paste two values, 20 and 28, into the allocation column. Then sort Project descending.

Visible positionRecord IDAllocated hours
0engineering28
1design20

An inverse patch that says "row 0 → 16, row 1 → 24" now writes to the wrong projects. The correct inverse is "design → 16, engineering → 24". Sorting is view state; undoing a data edit must not require undoing the view.

The history entry also needs the value expected at replay time. If someone has since changed Design to 22 hours, blindly restoring 16 destroys a newer update. A safe replay can refuse that edit instead.

Choose a single owner of writes ​

A React component, Zustand store, Redux reducer, or backend may own the source of truth. Do not let the grid write the same values independently and then ask the store to repeat those writes.

ResponsibilityOwner
Identify candidate cells, collect paste, apply column validationGrid
Identify records by persistent ID, enforce capacity and permissionsApplication store
Publish an accepted immutable snapshotApplication store
Record confirmed edits and request inverse operationsHistoryPlugin
Commit or reject an entire history replayApplication store

RevoGrid's EventManagerPlugin routes ordinary edits through externalEdit.apply. HistoryPlugin can use the same path for Undo and Redo. A single paste can create one history entry, even though it changes multiple records.

How editing, sorting, and undo work together ​

This example uses HistoryPlugin with externalEdit.history: true: the grid owns the undo and redo stacks, while your application store owns the data.

  1. Edit or paste. The grid sends proposed changes through externalEdit.apply. The store validates and commits them, publishes the updated rows, and then confirms the results. History records the confirmed changes with their record keys, previous values, and final values.
  2. Sort. The grid changes the visible row order. Record keys and edit history stay the same.
  3. Undo or redo. The grid uses those keys to request the recorded previous values for Undo, or the confirmed final values for Redo. The store checks current values, validates the replacements, and commits the whole replay before publishing its rows and confirming success.

Scroll horizontally on narrow screens.

A successful replay returns changed for every candidate, and History moves the entry to the other stack. If replay is rejected, the store must keep or restore all prior values; the entry stays on its current stack. RevoGrid cannot roll back your external store.

This diagram describes the loaded-row workflow used below. Both Undo and Redo preserve the active sort. For records outside the loaded view, see what happens when the source changes.

React example: immutable allocations ​

Install the React grid and RevoGrid Pro using the released packages. The following is a local-store example, not a network persistence implementation. It keeps both the store snapshot and the edit configuration stable across renders.

tsx
import { useMemo, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { RevoGrid } from '@revolist/react-datagrid';
import {
  EventManagerPlugin,
  HistoryPlugin,
  CellValidatePlugin,
  type EventManagerConfig,
  type ExternalEditResult,
} from '@revolist/revogrid-pro';
import '@revolist/revogrid-pro/styles.css';

type Allocation = {
  id: string;
  project: string;
  hours: number;
  available: number;
};

const plugins = [EventManagerPlugin, CellValidatePlugin, HistoryPlugin];
const columns = [
  { prop: 'project', name: 'Project', readonly: true, sortable: true },
  {
    prop: 'hours',
    name: 'Allocated hours',
    validate: (value: unknown) =>
      (typeof value === 'number' ||
       (typeof value === 'string' && value.trim() !== '')) &&
      Number.isInteger(Number(value)) && Number(value) >= 0,
  },
  { prop: 'available', name: 'Capacity', readonly: true },
];

export function AllocationGrid() {
  const [rows, setRows] = useState<Allocation[]>(() => [
    { id: 'design', project: 'Design', hours: 16, available: 24 },
    { id: 'engineering', project: 'Engineering', hours: 24, available: 32 },
  ]);
  const latest = useRef(rows);
  const grid = useRef<HTMLRevoGridElement>(null);

  const config = useMemo<EventManagerConfig>(() => ({
    externalEdit: {
      getRowKey: row => row.id,
      sourceVersion: 'project-allocations',
      history: true,
      apply({ candidates, historyDirection, signal }) {
        const next = new Map(latest.current.map(row => [row.id, row]));
        const results = candidates.map<ExternalEditResult>(candidate => {
          const { id, rowKey, prop, previousValue, proposedValue } = candidate;
          const row = typeof rowKey === 'string' ? next.get(rowKey) : undefined;
          const hours = typeof proposedValue === 'number' ||
            (typeof proposedValue === 'string' && proposedValue.trim() !== '')
            ? Number(proposedValue) : NaN;

          if (!row || prop !== 'hours') {
            return { id, status: 'rejected', message: 'Unknown allocation' };
          }
          if (historyDirection && row.hours !== previousValue) {
            return { id, status: 'rejected', message: 'Allocation changed' };
          }
          if (!Number.isInteger(hours) || hours < 0 || hours > row.available) {
            return { id, status: 'rejected', message: 'Invalid allocation' };
          }
          if (hours === row.hours) return { id, status: 'unchanged' };
          next.set(row.id, { ...row, hours });
          return { id, status: 'changed', value: hours };
        });

        signal.throwIfAborted();

        // A replay either restores every requested value or writes nothing.
        if (historyDirection && results.some(r => r.status !== 'changed')) {
          return results.map(r => r.status === 'changed'
            ? { id: r.id, status: 'unchanged' as const }
            : r);
        }

        if (results.some(r => r.status === 'changed')) {
          const snapshot = [...next.values()];
          latest.current = snapshot;
          flushSync(() => setRows(snapshot));
        }
        return results;
      },
    },
  }), []);

  async function replay(direction: 'undo' | 'redo') {
    const history = (await grid.current?.getPlugins())?.find(
      plugin => plugin instanceof HistoryPlugin,
    );
    if (direction === 'undo') history?.undo();
    else history?.redo();
  }

  return (
    <>
      <button onClick={() => void replay('undo')}>Undo</button>
      <button onClick={() => void replay('redo')}>Redo</button>
      <RevoGrid ref={grid} style={{ height: 280 }}
        source={rows} columns={columns} plugins={plugins}
        eventManager={config} range
      />
    </>
  );
}

The flushSync call is deliberate: RevoGrid needs the committed source to be published before the edit handler returns its outcomes. The ref gives the handler the latest snapshot rather than the state from the render that created the configuration. The example uses a synchronous store; do not hold a React render open while awaiting a network request.

The three possible candidate outcomes are changed, unchanged and rejected. A confirmed change can carry the actual normalized value written by the store. A rejected edit can carry a validation message. The candidate ID correlates the result with the request; it is not the record ID.

Try the paste, sort and undo workflow ​

Open the store-owned editing example in the Event Manager guide. It includes React, Vue, Angular and TypeScript implementations.

  1. Paste two lines containing 20 and 28 into the Allocated hours column starting at Design.
  2. Sort Project so Engineering is first.
  3. Press Undo. Verify Engineering is 24, Design is 16, and the sort remains unchanged.
  4. Redo. Verify Engineering is 28 and Design is 20.
  5. Attempt to paste values exceeding both capacities. Verify the store remains unchanged and that the rejected attempt does not create an additional history step.

Use the explicit Undo button when focus is on a toolbar; keyboard shortcuts may otherwise belong to another component.

What happens when the source changes? ​

A new array is not necessarily a new dataset. With immutable updates, keep sourceVersion constant for the same logical dataset and provide getRowKey for unique keys. Change the version when switching, for example, from project A to project B. Otherwise a command from one project may target a record in another.

The simple history: true mode resolves targets in the loaded view. If a target is missing, filtered out, or its expected value differs, replay can remain on the existing stack. For unloaded server pages, the external history command adapter sends ID-based commands to the store instead of relying on the visible view. The server must check permissions, expected values, revisions and atomicity. A lost response is not proof of failure; use operation IDs and receipt recovery rather than repeating an uncertain write.

An aborted request is likewise not proof that the server rolled back. Coordinate writes with the store's revision or ordering mechanism and handle externalediterror to surface failures. For one command that changes several grids or related entities, an application-owned history stack may be the better boundary.

How other grid history models differ ​

AG Grid's edit history documentation explicitly notes that operations such as sorting, filtering, grouping and non-edit data updates clear its built-in edit stacks. An application can implement its own durable store history around that behavior.

Handsontable's UndoRedo documentation distinguishes UI edits from programmatic modifications. Its interactive history demo also covers structural actions and sorting. These are different contracts; whether a particular external store replay works should be tested separately.

The differentiator in this RevoGrid workflow is not undo itself. It is the explicit request/result contract between the grid's history and the store that owns the write.

For a smaller spreadsheet that owns history entirely in React, see our Core spreadsheet tutorial. For a production allocation workflow, try RevoGrid Pro and the History guide.

For a broader comparison, see RevoGrid vs AG Grid and RevoGrid vs Handsontable.