I am currently implementing a grid state persistence in localStorage so that any user that did previous changes in the grid state will get it back when revisiting:
Targeted changes to save
- columns order/sizing/visibility
- search
- sorting
I am trying to use the DataGridPremium onStateChange event, although the event is fired when the state is initialize. I don't want that since I don't want to save the state when the user did not no change anything to the grid.
Is there a way that I could skip the initialState change event?
May be an event I could bind to that would tell me the grid finished loading his initialState and save a component state "gridInitialized".
Here's a snippet of my grid:
<DataGridPremium
initialState={{
...initialState,
sorting: {
// Sort first column by default.
sortModel: [{ field: columns[0].field, sort: 'asc' }],
...initialState?.sorting,
},
}}
onStateChange={handleStateChangeEvent}
{ ...otherProps }
/>
And to my handleStateChangeEvent function:
const handleStateChangeEvent: GridEventListener<'stateChange'> = useCallback(() => {
// if (!gridInitialized) return; // ???
saveState(
{
...apiRef.current.exportState(),
preferencePanel: { open: false },
},
STATE_KEY
);
}, [STATE_KEY, apiRef]);
I tried to only bind on specific DataGridPremium changeEvent, but I missed changes I wanted to capture.
For instance:
<DataGridPremium
initialState={{
...initialState,
sorting: {
// Sort first column by default.
sortModel: [{ field: columns[0].field, sort: 'asc' }],
...initialState?.sorting,
},
}}
onColumnOrderChange={handleEvent}
onColumnWidthChange={handleEvent}
onPreferencePanelClose={handleEvent}
{ ...otherProps }
/>
and
// Save state to local storage
const handleEvent: GridEventListener<
'columnOrderChange' | 'columnWidthChange' | 'preferencePanelClose'
> = useCallback(
() => {
saveState(
{
...apiRef.current.exportState(),
preferencePanel: { open: false },
},
STATE_KEY
);
},
[STATE_KEY, apiRef]
);
Thank you