Skip to content

Commit

Permalink
[DataGrid] Add possibility of null in the return type of the `useGr…
Browse files Browse the repository at this point in the history
…idApiRef()` hook (#16353)

Signed-off-by: Armin Mehinovic <[email protected]>
  • Loading branch information
arminmeh authored Jan 27, 2025
1 parent 6b0c8f4 commit 4ebe54a
Show file tree
Hide file tree
Showing 150 changed files with 1,161 additions and 1,115 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ export default function AccessDisabledColumnFeatures() {

return (
<div style={{ width: '100%' }}>
<Button onClick={() => apiRef.current.sortColumn('firstName', 'asc')}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', 'asc')}>
Sort by ASC
</Button>
<Button onClick={() => apiRef.current.sortColumn('firstName', 'desc')}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', 'desc')}>
Sort by DESC
</Button>
<Button onClick={() => apiRef.current.sortColumn('firstName', null)}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', null)}>
Remove sort
</Button>
<Box sx={{ height: 400 }}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ export default function AccessDisabledColumnFeatures() {

return (
<div style={{ width: '100%' }}>
<Button onClick={() => apiRef.current.sortColumn('firstName', 'asc')}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', 'asc')}>
Sort by ASC
</Button>
<Button onClick={() => apiRef.current.sortColumn('firstName', 'desc')}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', 'desc')}>
Sort by DESC
</Button>
<Button onClick={() => apiRef.current.sortColumn('firstName', null)}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', null)}>
Remove sort
</Button>
<Box sx={{ height: 400 }}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<Button onClick={() => apiRef.current.sortColumn('firstName', 'asc')}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', 'asc')}>
Sort by ASC
</Button>
<Button onClick={() => apiRef.current.sortColumn('firstName', 'desc')}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', 'desc')}>
Sort by DESC
</Button>
<Button onClick={() => apiRef.current.sortColumn('firstName', null)}>
<Button onClick={() => apiRef.current?.sortColumn('firstName', null)}>
Remove sort
</Button>
<Box sx={{ height: 400 }}>
Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/api-object/UseGridApiRef.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function UseGridApiRef() {

const apiRef = useGridApiRef();

const handleGoToPage1 = () => apiRef.current.setPage(1);
const handleGoToPage1 = () => apiRef.current?.setPage(1);

return (
<Stack spacing={1} sx={{ width: '100%' }} alignItems="flex-start">
Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/api-object/UseGridApiRef.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function UseGridApiRef() {

const apiRef = useGridApiRef();

const handleGoToPage1 = () => apiRef.current.setPage(1);
const handleGoToPage1 = () => apiRef.current?.setPage(1);

return (
<Stack spacing={1} sx={{ width: '100%' }} alignItems="flex-start">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default function CellSelectionFormulaField() {
const updates = [];

Object.entries(cellSelectionModel).forEach(([id, fields]) => {
const updatedRow = { ...apiRef.current.getRow(id) };
const updatedRow = { ...apiRef.current?.getRow(id) };

Object.entries(fields).forEach(([field, isSelected]) => {
if (isSelected) {
Expand All @@ -40,10 +40,14 @@ export default function CellSelectionFormulaField() {
updates.push(updatedRow);
});

apiRef.current.updateRows(updates);
apiRef.current?.updateRows(updates);
}, [apiRef, cellSelectionModel, value]);

React.useEffect(() => {
if (apiRef.current === null) {
return;
}

const selectedCells = apiRef.current.getSelectedCellsAsArray();
setNumberOfSelectedCells(selectedCells.length);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default function CellSelectionFormulaField() {
const updates: GridRowModelUpdate[] = [];

Object.entries(cellSelectionModel).forEach(([id, fields]) => {
const updatedRow = { ...apiRef.current.getRow(id) };
const updatedRow = { ...apiRef.current?.getRow(id) };

Object.entries(fields).forEach(([field, isSelected]) => {
if (isSelected) {
Expand All @@ -52,10 +52,14 @@ export default function CellSelectionFormulaField() {
updates.push(updatedRow);
});

apiRef.current.updateRows(updates);
apiRef.current?.updateRows(updates);
}, [apiRef, cellSelectionModel, value]);

React.useEffect(() => {
if (apiRef.current === null) {
return;
}

const selectedCells = apiRef.current.getSelectedCellsAsArray();
setNumberOfSelectedCells(selectedCells.length);

Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/column-dimensions/ColumnAutosizing.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export default function ColumnAutosizing() {
>
<Button
variant="outlined"
onClick={() => apiRef.current.autosizeColumns(autosizeOptions)}
onClick={() => apiRef.current?.autosizeColumns(autosizeOptions)}
>
Autosize columns
</Button>
Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/column-dimensions/ColumnAutosizing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export default function ColumnAutosizing() {
>
<Button
variant="outlined"
onClick={() => apiRef.current.autosizeColumns(autosizeOptions)}
onClick={() => apiRef.current?.autosizeColumns(autosizeOptions)}
>
Autosize columns
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,14 @@ export default function ColumnAutosizingAsync() {
.then((data) => {
ReactDOM.flushSync(() => {
setIsLoading(false);
apiRef.current.updateRows(data.rows);
apiRef.current?.updateRows(data.rows);
});
})
// `sleep`/`setTimeout` is required because `.updateRows` is an
// async function throttled to avoid choking on frequent changes.
.then(() => sleep(0))
.then(() =>
apiRef.current.autosizeColumns({
apiRef.current?.autosizeColumns({
includeHeaders: true,
includeOutliers: true,
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,14 @@ export default function ColumnAutosizingAsync() {
.then((data) => {
ReactDOM.flushSync(() => {
setIsLoading(false);
apiRef.current.updateRows(data.rows);
apiRef.current?.updateRows(data.rows);
});
})
// `sleep`/`setTimeout` is required because `.updateRows` is an
// async function throttled to avoid choking on frequent changes.
.then(() => sleep(0))
.then(() =>
apiRef.current.autosizeColumns({
apiRef.current?.autosizeColumns({
includeHeaders: true,
includeOutliers: true,
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default function ColumnAutosizingDynamicRowHeight() {

return (
<div style={{ width: '100%' }}>
<Button onClick={() => apiRef.current.autosizeColumns(autosizeOptions)}>
<Button onClick={() => apiRef.current?.autosizeColumns(autosizeOptions)}>
Autosize Columns
</Button>
<div style={{ height: 400, width: '100%' }}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export default function ColumnAutosizingDynamicRowHeight() {

return (
<div style={{ width: '100%' }}>
<Button onClick={() => apiRef.current.autosizeColumns(autosizeOptions)}>
<Button onClick={() => apiRef.current?.autosizeColumns(autosizeOptions)}>
Autosize Columns
</Button>
<div style={{ height: 400, width: '100%' }}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export default function ColumnAutosizingGroupedRows() {
});

React.useEffect(() => {
return apiRef.current.subscribeEvent('rowExpansionChange', (params) => {
return apiRef.current?.subscribeEvent('rowExpansionChange', (params) => {
if (params.childrenExpanded) {
apiRef.current.autosizeColumns({ includeOutliers: true });
apiRef.current?.autosizeColumns({ includeOutliers: true });
}
});
}, [apiRef]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export default function ColumnAutosizingGroupedRows() {
});

React.useEffect(() => {
return apiRef.current.subscribeEvent('rowExpansionChange', (params) => {
return apiRef.current?.subscribeEvent('rowExpansionChange', (params) => {
if (params.childrenExpanded) {
apiRef.current.autosizeColumns({ includeOutliers: true });
apiRef.current?.autosizeColumns({ includeOutliers: true });
}
});
}, [apiRef]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default function ColumnMenuGridPremiumSnap() {
React.useEffect(() => {
// To avoid an issue around Popper being open before the ref is set.
Promise.resolve().then(() => {
apiRef.current.showColumnMenu('gross');
apiRef.current?.showColumnMenu('gross');
console.log('after showColumnMenu');
});
}, [apiRef]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default function ColumnMenuGridPremiumSnap() {
React.useEffect(() => {
// To avoid an issue around Popper being open before the ref is set.
Promise.resolve().then(() => {
apiRef.current.showColumnMenu('gross');
apiRef.current?.showColumnMenu('gross');
console.log('after showColumnMenu');
});
}, [apiRef]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default function ColumnPinningDynamicRowHeight() {
}, []);

React.useLayoutEffect(() => {
apiRef.current.resetRowHeights();
apiRef.current?.resetRowHeights();
}, [apiRef, showEditDelete]);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export default function ColumnPinningDynamicRowHeight() {
}, []);

React.useLayoutEffect(() => {
apiRef.current.resetRowHeights();
apiRef.current?.resetRowHeights();
}, [apiRef, showEditDelete]);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export default function ColumnSizingPersistWidthOrder() {
}

const useColumnsState = (
apiRef: React.RefObject<GridApiPro>,
apiRef: React.RefObject<GridApiPro | null>,
columns: GridColDef[],
) => {
const [widths, setWidths] = React.useState<Record<GridColDef['field'], number>>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function ColumnSelectorGridSnap() {
const apiRef = useGridApiRef();

React.useEffect(() => {
apiRef.current.showPreferences(GridPreferencePanelsValue.columns);
apiRef.current?.showPreferences(GridPreferencePanelsValue.columns);
}, [apiRef]);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function ColumnSelectorGridSnap() {
const apiRef = useGridApiRef();

React.useEffect(() => {
apiRef.current.showPreferences(GridPreferencePanelsValue.columns);
apiRef.current?.showPreferences(GridPreferencePanelsValue.columns);
}, [apiRef]);

return (
Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/components/CustomColumnMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export default function CustomColumnMenu() {
onClick={(event) => {
event.stopPropagation();
setColor((current) => (current === 'primary' ? 'secondary' : 'primary'));
apiRef.current.showColumnMenu('default');
apiRef.current?.showColumnMenu('default');
}}
>
Toggle menu background
Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/components/CustomColumnMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export default function CustomColumnMenu() {
onClick={(event) => {
event.stopPropagation();
setColor((current) => (current === 'primary' ? 'secondary' : 'primary'));
apiRef.current.showColumnMenu('default');
apiRef.current?.showColumnMenu('default');
}}
>
Toggle menu background
Expand Down
9 changes: 6 additions & 3 deletions docs/data/data-grid/demo/PopularFeaturesDemo.js
Original file line number Diff line number Diff line change
Expand Up @@ -453,11 +453,14 @@ export default function PopularFeaturesDemo() {

const onRowClick = React.useCallback(
(params) => {
const rowNode = apiRef.current.getRowNode(params.id);
const rowNode = apiRef.current?.getRowNode(params.id);
if (rowNode && rowNode.type === 'group') {
apiRef.current.setRowChildrenExpansion(params.id, !rowNode.childrenExpanded);
apiRef.current?.setRowChildrenExpansion(
params.id,
!rowNode.childrenExpanded,
);
} else {
apiRef.current.toggleDetailPanel(params.id);
apiRef.current?.toggleDetailPanel(params.id);
}
},
[apiRef],
Expand Down
9 changes: 6 additions & 3 deletions docs/data/data-grid/demo/PopularFeaturesDemo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -474,11 +474,14 @@ export default function PopularFeaturesDemo() {

const onRowClick = React.useCallback<GridEventListener<'rowClick'>>(
(params) => {
const rowNode = apiRef.current.getRowNode(params.id);
const rowNode = apiRef.current?.getRowNode(params.id);
if (rowNode && rowNode.type === 'group') {
apiRef.current.setRowChildrenExpansion(params.id, !rowNode.childrenExpanded);
apiRef.current?.setRowChildrenExpansion(
params.id,
!rowNode.childrenExpanded,
);
} else {
apiRef.current.toggleDetailPanel(params.id);
apiRef.current?.toggleDetailPanel(params.id);
}
},
[apiRef],
Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/events/SubscribeToEventsApiRef.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default function SubscribeToEventsApiRef() {
};

// The `subscribeEvent` method will automatically unsubscribe in the cleanup function of the `useEffect`.
return apiRef.current.subscribeEvent('rowClick', handleRowClick);
return apiRef.current?.subscribeEvent('rowClick', handleRowClick);
}, [apiRef]);

return (
Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/events/SubscribeToEventsApiRef.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default function SubscribeToEventsApiRef() {
};

// The `subscribeEvent` method will automatically unsubscribe in the cleanup function of the `useEffect`.
return apiRef.current.subscribeEvent('rowClick', handleRowClick);
return apiRef.current?.subscribeEvent('rowClick', handleRowClick);
}, [apiRef]);

return (
Expand Down
9 changes: 7 additions & 2 deletions docs/data/data-grid/filtering-recipes/FilteredRowCount.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,12 @@ export default function FilteredRowCount() {

const getFilteredRowsCount = React.useCallback(
(filterModel) => {
const { filteredRowsLookup } = apiRef.current.getFilterState(filterModel);
const filterState = apiRef.current?.getFilterState(filterModel);
if (!filterState) {
return 0;
}

const { filteredRowsLookup } = filterState;
return Object.keys(filteredRowsLookup).filter(
(rowId) => filteredRowsLookup[rowId] === true,
).length;
Expand All @@ -72,7 +77,7 @@ export default function FilteredRowCount() {
return (
<Button
key={label}
onClick={() => apiRef.current.setFilterModel(filterModel)}
onClick={() => apiRef.current?.setFilterModel(filterModel)}
variant="outlined"
>
{label} {count !== undefined ? `(${count})` : ''}
Expand Down
9 changes: 7 additions & 2 deletions docs/data/data-grid/filtering-recipes/FilteredRowCount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,12 @@ export default function FilteredRowCount() {

const getFilteredRowsCount = React.useCallback(
(filterModel: GridFilterModel) => {
const { filteredRowsLookup } = apiRef.current.getFilterState(filterModel);
const filterState = apiRef.current?.getFilterState(filterModel);
if (!filterState) {
return 0;
}

const { filteredRowsLookup } = filterState;
return Object.keys(filteredRowsLookup).filter(
(rowId) => filteredRowsLookup[rowId] === true,
).length;
Expand All @@ -72,7 +77,7 @@ export default function FilteredRowCount() {
return (
<Button
key={label}
onClick={() => apiRef.current.setFilterModel(filterModel)}
onClick={() => apiRef.current?.setFilterModel(filterModel)}
variant="outlined"
>
{label} {count !== undefined ? `(${count})` : ''}
Expand Down
2 changes: 1 addition & 1 deletion docs/data/data-grid/filtering/MultiFilteringPanelSnap.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default function MultiFilteringPanelSnap() {
const apiRef = useGridApiRef();

useEnhancedEffect(() => {
apiRef.current.showFilterPanel();
apiRef.current?.showFilterPanel();
}, [apiRef]);

return (
Expand Down
Loading

0 comments on commit 4ebe54a

Please sign in to comment.