Persist grid state to localStorage
Save sorting, filters, column layout, selection and expansion with getState() and restore them with setState() on the next visit.
Users expect a grid to look the way they left it. This recipe saves the whole view state, not only the column layout, to localStorage whenever it changes and restores it when the page loads.
Loading demo…
View source
Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.
import { createGrid, type ColumnDef, type GridState } from '@birchui/core';
import {
button,
docsTheme,
formatCurrency,
layout,
makeOrders,
onDocsThemeChange,
revenueOf,
type Order,
} from './_shared';
export const meta = { title: 'Persist grid state', height: 440 };
const STORAGE_KEY = 'birchui-docs:orders-grid-state';
const columns: ColumnDef<Order>[] = [
{ field: 'id', header: 'Order', width: 110 },
{ field: 'customer', header: 'Customer', flex: 1, minWidth: 170, filter: 'text' },
{ field: 'region', header: 'Region', width: 140, filter: 'set' },
{ field: 'status', header: 'Status', width: 120, filter: 'set' },
{ field: 'orderDate', header: 'Ordered', type: 'date', width: 130 },
{ id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency },
];
function loadState(): Partial<GridState> | null {
try {
const saved = localStorage.getItem(STORAGE_KEY);
return saved ? (JSON.parse(saved) as Partial<GridState>) : null;
} catch {
return null;
}
}
function saveState(state: GridState): void {
try {
const { scroll: _scroll, focusedCell: _focus, ...durable } = state;
localStorage.setItem(STORAGE_KEY, JSON.stringify(durable));
} catch {
// Storage can be full or disabled; the grid keeps working without it.
}
}
function clearState(): void {
try {
localStorage.removeItem(STORAGE_KEY);
} catch {
// Ignored for the same reason as in saveState.
}
}
export default function mount(el: HTMLElement): () => void {
const { toolbar, body, status } = layout(el);
const grid = createGrid<Order>(body, {
columns,
rows: makeOrders(300, 11),
getRowId: (order) => order.id,
floatingFilters: true,
rowSelection: 'multiple',
theme: docsTheme(),
ariaLabel: 'Orders with saved layout',
});
const saved = loadState();
if (saved) grid.setState(saved);
status.textContent = saved ? 'Restored the saved layout.' : 'Sort, filter, resize or select, then reload the page.';
let timer: ReturnType<typeof setTimeout> | undefined;
const offState = grid.on('stateChanged', ({ state }) => {
clearTimeout(timer);
timer = setTimeout(() => {
saveState(state);
status.textContent = `Saved: ${state.sort.length} sort keys, ${Object.keys(state.filterModel).length} filters, ${state.selectedRowIds.length} selected rows.`;
}, 300);
});
toolbar.append(
'Changes are saved to localStorage.',
button('Reset layout', () => {
clearTimeout(timer);
clearState();
grid.setState({ sort: [], filterModel: {}, quickFilter: '', selectedRowIds: [] });
status.textContent = 'Saved layout cleared.';
}),
);
const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
return () => {
clearTimeout(timer);
offState();
stopTheme();
grid.destroy();
};
}1. Read and write the state#
getState() returns a plain, JSON-serializable GridState object. setState() accepts all of it or any subset.
import type { GridState } from '@birchui/core';
const STORAGE_KEY = 'orders-grid-state:v1';
export function loadGridState(): Partial<GridState> | null {
try {
const saved = localStorage.getItem(STORAGE_KEY);
return saved ? (JSON.parse(saved) as Partial<GridState>) : null;
} catch {
return null;
}
}
export function saveGridState(state: GridState): void {
const { scroll, focusedCell, ...durable } = state;
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(durable));
} catch {
// Quota exceeded or storage disabled: keep the in-memory layout only.
}
}The scroll and focusedCell fields are dropped here because a restored scroll position on a fresh page load is usually surprising. Keep them if you restore state inside a single-page app when the user navigates back.
2. Restore on load and save on change#
import { createGrid, type ColumnDef } from '@birchui/core';
import { loadGridState, saveGridState } from './grid-state-storage';
import type { Order } from './orders';
const columns: ColumnDef<Order>[] = [
{ field: 'id', header: 'Order', width: 110 },
{ field: 'customer', header: 'Customer', flex: 1, filter: 'text' },
{ field: 'region', header: 'Region', filter: 'set' },
{ field: 'status', header: 'Status', filter: 'set' },
{ field: 'total', header: 'Total', type: 'number' },
];
const grid = createGrid<Order>(document.querySelector<HTMLElement>('#orders')!, {
columns,
rows: orders,
getRowId: (order) => order.id,
rowSelection: 'multiple',
floatingFilters: true,
});
const saved = loadGridState();
if (saved) grid.setState(saved);
let timer: ReturnType<typeof setTimeout> | undefined;
grid.on('stateChanged', ({ state }) => {
clearTimeout(timer);
timer = setTimeout(() => saveGridState(state), 300);
});Call setState() after the rows are loaded. Selected and expanded row ids only apply to rows that exist, so restoring before an asynchronous fetch finishes loses them.
How it works#
GridState contains:
| Field | Contents |
|---|---|
columns |
Width, pinning, visibility and order of each column, the same as getColumnState() |
sort, filterModel, quickFilter |
The sort and filter models |
page |
The current page when pagination is on |
expandedRowIds, selectedRowIds |
Ids from getRowId |
focusedCell, scroll |
Focus and scroll position |
modules |
State contributed by installed modules, keyed by module |
stateChanged is batched: several changes in the same task, such as a sort followed by a filter in one handler, produce one event. Scrolling also emits it, which is why the save is debounced.
Pitfalls#
- Custom filters are not serializable. A
{ type: 'custom', test }filter holds a function, so it is left out of the saved filter model. Recreate it in code aftersetState(). - Version the key. When you rename or remove columns, saved state can refer to columns that no longer exist. Bump the suffix in
STORAGE_KEYwhen the column set changes.setState()ignores invalid values and logs a warning naming them. - Set
getRowId. Without it row ids are positions, and a saved selection points at different rows after the data changes. - Storage can throw. Private browsing modes and full quotas make
setItemthrow; always wrap storage calls.
Related#
- Saving and restoring column state for the column layout alone.
- Filter models and the sort model.
- Row IDs.
GridApireference.