Saving and restoring state
Capture the whole grid view as JSON with getState, restore it with setState, and save it whenever it changes.
getState() returns the whole view as plain JSON: column order, widths, pinning and visibility, sort, filters, the quick filter, the page, expanded and selected row ids, the focused cell, the scroll position, and state from modules. setState() applies any part of it, and stateChanged fires once per task after any of these change.
import { createGrid, type GridState } from '@birchui/core';
const STORAGE_KEY = 'orders-grid:v1';
function loadState(): Partial<GridState> | null {
try {
const saved = localStorage.getItem(STORAGE_KEY);
return saved ? (JSON.parse(saved) as Partial<GridState>) : null;
} catch {
return null;
}
}
const grid = createGrid<Order>(el, { columns, rows: orders, getRowId: (order) => order.id });
const saved = loadState();
if (saved) grid.setState(saved);
function saveState(state: GridState): boolean {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
return true;
} catch {
return false;
}
}
grid.on('stateChanged', ({ state }) => saveState(state));What to keep in mind#
- Load rows first. Selection and expansion refer to row ids, so call
setState()once the rows are in the grid, and give the grid agetRowId. - Apply only what you want.
setState({ columns, sort })restores the layout and sort but keeps the current filters. Leave outscrollandfocusedCellwhen you restore state on a different screen size. - Custom filters are skipped. Filters with
type: 'custom'hold a function and cannot be serialized, so they are left out. - Invalid parts are skipped. A malformed section logs one console warning and the rest is applied, so an old saved state does not break the grid. Version your storage key when your columns change significantly.
- Saving often is cheap.
stateChangedis batched to once per task; debounce it yourself if you send state to a server.
Column state only#
When you only need the column layout, getColumnState() and applyColumnState() work on the columns part, and columnStateChanged fires when it changes:
State from modules#
Modules store their own state under state.modules[name]. Grid Pro's side bar, for example, saves which panel is open there. A module registers a provider with internals.addStateProvider(name, { get, set, subscribe }); the optional subscribe(notify) lets it report its own changes so stateChanged fires.
Related#
- Persist grid state to localStorage, a complete recipe with a reset button.
- Column operations
- Modules