Share one rows store between grids
Since 1.6.0
createRowsStore and the rowsStore option were added. Import them from maxgrid or @maxgrid/core.
When several grids show the same rows (a master and a summary, a list and a detail), you do not have to keep the row arrays in step by hand. Make one store and give it to each grid as rowsStore: the data is shared and each grid keeps its own way of looking at it.
ts
import { createGrid, createRowsStore } from 'maxgrid';
const store = createRowsStore(rows, { rowKey: 'id' });
const master = createGrid(masterEl, { columns: masterColumns, rowsStore: store });
const summary = createGrid(summaryEl, { columns: summaryColumns, rowsStore: store });- Sort, filter, grouping, selection, columns and the undo history are per grid.
rowsandrowKeycome from the store, so they cannot be used with it (aninvalid-optionerror). Changingrows,rowKeyorrowsStorewithsetOptionsis refused the same way. To change data, use the store or the grid's row API.- Duplicate or missing row keys raise the same error as a grid, and the store is left unchanged.
Store API
| Method | What it does |
|---|---|
getRows(), getRow(key) | Read rows |
setRows(rows) | Replace all rows |
updateRow(key, patch) | Merge patch into the row. false for an unknown key; a patch that changes the key throws |
addRows(rows, at?) | Insert at at (the end if omitted) |
removeRows(keys) | Remove rows and return how many were removed |
transaction(fn) | Group the changes in fn into one notification; if fn throws everything is rolled back |
subscribe(listener) | Receives { reason, count }; call the returned function to stop |
How the grids stay in step
- A cell edit, row add or remove, paste, fill or undo in one grid is written to the store. The other grids apply it once in the same frame (
requestAnimationFrame, or a microtask where there is none). - The receiving grid keeps its scroll position and focus, and drops selected keys of rows that are gone. No flash is added; a grid with change marking (
saveMode) marks the change as usual. - The receiving grid emits
rowsChangedonce per change. If several changes land in one frame they are applied in the order they happened. - Undo: an undo in grid A comes from A's history and is written to the store, so B follows. B's own history does not record it, and B's older entries for the same row are not rewritten (undoing there can write that older value back to the store). When one grid replaces all rows (
setRows), the history of the receiving grids is cleared. - Cleanup:
destroy()unsubscribes the grid. The store can outlive its grids, and you can create a new grid on the same store. CallingcreateRowsStoreduring server rendering is safe (it uses no browser API).
To keep horizontal scroll or column widths of the two grids aligned, use alignGrids as well.
Gallery example: shared-store-two-grids
Gallery example: shared-store-master-summary
Gallery example: shared-store-filters-differ