Data Grid - 서버 쪽 트리 데이터
Data Grid - 서버 쪽 트리 데이터 (Server-side tree data)
Data Source 레이어를 사용해 Data Grid에서 지연 로딩(lazy-loading) 서버 쪽 트리 데이터를 구현할 수 있어요.
본문
트리는 데이터를 부모-자식 관계로 구성하는 계층적 데이터 구조예요. Data Grid Pro는 Data Source 레이어를 사용해 중첩된 자식을 가진 그룹 행을 렌더링하는 서버 쪽 트리 데이터를 처리할 수 있어요.
:::info 클라이언트 쪽 트리 데이터는 Tree data (client side) 문서를 참고하세요. :::
사전 조건 (Prerequisites)
서버 쪽 트리 데이터 기능은 클라이언트 쪽 버전의 확장이므로, 진행하기 전에 Tree data (client side)를 검토해 기본 데이터 구조와 핵심 구현을 이해하는 것을 권장해요.
자식의 지연 로딩을 포함해 서버에서 트리 데이터를 동적으로 로드하려면 Data Source를 만들고 Server-side data overview에 설명된 대로 dataSource prop을 Data Grid에 전달해야 해요.
서버 쪽 트리 데이터 구현 (Implementing server-side tree data)
Data Source는 트리 데이터를 처리하기 위해 다음 props가 필요해요:
getGroupKey(): 행에 대한 그룹 키를 반환해요.getChildrenCount(): 행의 자식 수를 반환해요. 자식이 있지만 개수를 알 수 없으면-1을 반환해요.
const customDataSource: GridDataSource = {
getRows: async (params) => {
// Fetch the data from the server
},
getGroupKey: (row) => {
// Return the group key for the row, e.g. `name`
return row.name;
},
getChildrenCount: (row) => {
// Return the number of children for the row
return row.childrenCount;
},
};
getRows() 콜백은 getGroupKey()에서 각 중첩 레벨에 제공된 키에 해당하는 groupKeys 매개변수를 받아요. 서버에서 groupKeys를 사용해 주어진 중첩 레벨의 행을 추출해요.
const getRows: async (params) => {
const urlParams = new URLSearchParams({
// Example: JSON.stringify(['Billy Houston', 'Lora Dean'])
groupKeys: JSON.stringify(params.groupKeys),
});
const getRowsResponse = await fetchRows(
// Server should extract the rows for the nested level based on `groupKeys`
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
}
다음 트리 데이터 예시는 서버에서 필터링, 정렬, 페이지네이션을 지원해요. 또한 기본적으로 데이터를 캐시해요.
import * as React from 'react';
import {
DataGridPro,
useGridApiRef,
GridInitialState,
GridDataSource,
} from '@mui/x-data-grid-pro';
import Button from '@mui/material/Button';
import { useMockServer } from '@mui/x-data-grid-generator';
const pageSizeOptions = [5, 10, 50];
const dataSetOptions = {
dataSet: 'Employee' as const,
rowLength: 1000,
editable: true,
treeData: { maxDepth: 3, groupingField: 'name', averageChildren: 5 },
};
export default function ServerSideTreeData() {
const apiRef = useGridApiRef();
const { fetchRows, editRow, columns, initialState } =
useMockServer(dataSetOptions);
const initialStateWithPagination: GridInitialState = React.useMemo(
() => ({
...initialState,
pagination: {
paginationModel: {
pageSize: 5,
},
rowCount: 0,
},
}),
[initialState],
);
const dataSource: GridDataSource = React.useMemo(
() => ({
getRows: async (params) => {
const urlParams = new URLSearchParams({
paginationModel: JSON.stringify(params.paginationModel),
filterModel: JSON.stringify(params.filterModel),
sortModel: JSON.stringify(params.sortModel),
groupKeys: JSON.stringify(params.groupKeys),
});
const getRowsResponse = await fetchRows(
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
},
updateRow: async (params) => {
const syncedRow = await editRow(params.rowId, params.updatedRow);
return syncedRow;
},
getGroupKey: (row) => row[dataSetOptions.treeData.groupingField],
getChildrenCount: (row) => row.descendantCount,
}),
[fetchRows, editRow],
);
return (
<div style={{ width: '100%' }}>
<Button onClick={() => apiRef.current?.dataSource.cache.clear()}>
Reset cache
</Button>
<div style={{ height: 400 }}>
<DataGridPro
columns={columns}
dataSource={dataSource}
treeData
apiRef={apiRef}
pagination
pageSizeOptions={pageSizeOptions}
initialState={initialStateWithPagination}
showToolbar
/>
</div>
</div>
);
}
:::info
Data Source 데모는 서버 쪽 데이터 페칭을 시뮬레이션하기 위해 useMockServer() 유틸리티 함수를 사용해요. 실제 시나리오에서는 이를 직접 작성한 서버 쪽 데이터 페칭 로직으로 교체하면 돼요.
브라우저 콘솔의 Info 섹션을 열어 요청과 그에 대한 응답으로 페치되는 데이터를 볼 수 있어요. :::
동적 데이터 갱신 처리 (Handle dynamic data updates)
동적 서버 쪽 트리 데이터에 대한 새 값을 계속 가져오려면 dataSourceRevalidateMs prop을 사용해요. 이는 백그라운드에서 현재 서버 쪽 쿼리를 재검증하고 최신 데이터로 Data Grid를 갱신하는 폴링 타이머를 시작해요.
아래 데모는 dataSourceRevalidateMs={2_000}을 사용하고 캐시를 비활성화해 주기적인 갱신을 보이게 해요. 또한 중첩된 주식 계층 구조에서 안정적인 행 ID를 사용해 갱신 후에도 확장된 행이 확장된 상태를 유지해요.
import * as React from 'react';
import {
DataGridPro,
GridColDef,
GridDataSource,
GridGetRowsParams,
GridGetRowsResponse,
GridRenderCellParams,
} from '@mui/x-data-grid-pro';
import Typography from '@mui/material/Typography';
import { alpha } from '@mui/material/styles';
interface TreeStockRow {
id: string;
name: string;
symbol: string;
price: number;
volume: number;
childrenCount: number;
}
type StockLeaf = {
symbol: string;
name: string;
basePrice: number;
baseVolume: number;
};
type StockIndustry = {
id: string;
name: string;
stocks: StockLeaf[];
};
type StockSector = {
id: string;
name: string;
industries: StockIndustry[];
};
const PRICE_ROUNDING_FACTOR = 100;
const STOCK_TREE: StockSector[] = [
{
id: 'tech',
name: 'Technology',
industries: [
{
id: 'software',
name: 'Software',
stocks: [
{
symbol: 'MSFT',
name: 'Microsoft',
basePrice: 430,
baseVolume: 18_000_000,
},
{ symbol: 'ADBE', name: 'Adobe', basePrice: 560, baseVolume: 2_900_000 },
{
symbol: 'CRM',
name: 'Salesforce',
basePrice: 310,
baseVolume: 4_700_000,
},
],
},
{
id: 'internet',
name: 'Internet Platforms',
stocks: [
{
symbol: 'GOOGL',
name: 'Alphabet',
basePrice: 195,
baseVolume: 24_000_000,
},
{ symbol: 'META', name: 'Meta', basePrice: 505, baseVolume: 13_000_000 },
{ symbol: 'NFLX', name: 'Netflix', basePrice: 660, baseVolume: 5_000_000 },
],
},
],
},
{
id: 'finance',
name: 'Financial Services',
industries: [
{
id: 'banks',
name: 'Banks',
stocks: [
{ symbol: 'JPM', name: 'JPMorgan', basePrice: 242, baseVolume: 9_500_000 },
{
symbol: 'BAC',
name: 'Bank of America',
basePrice: 47,
baseVolume: 44_000_000,
},
{ symbol: 'C', name: 'Citigroup', basePrice: 74, baseVolume: 14_000_000 },
],
},
{
id: 'payments',
name: 'Payments',
stocks: [
{ symbol: 'V', name: 'Visa', basePrice: 345, baseVolume: 7_000_000 },
{
symbol: 'MA',
name: 'Mastercard',
basePrice: 505,
baseVolume: 3_300_000,
},
{ symbol: 'PYPL', name: 'PayPal', basePrice: 82, baseVolume: 12_000_000 },
],
},
],
},
{
id: 'energy',
name: 'Energy',
industries: [
{
id: 'integrated',
name: 'Integrated Oil & Gas',
stocks: [
{
symbol: 'XOM',
name: 'Exxon Mobil',
basePrice: 120,
baseVolume: 15_000_000,
},
{ symbol: 'CVX', name: 'Chevron', basePrice: 170, baseVolume: 8_300_000 },
{ symbol: 'SHEL', name: 'Shell', basePrice: 74, baseVolume: 7_400_000 },
],
},
{
id: 'renewables',
name: 'Renewables',
stocks: [
{
symbol: 'NEE',
name: 'NextEra Energy',
basePrice: 76,
baseVolume: 11_000_000,
},
{
symbol: 'ENPH',
name: 'Enphase Energy',
basePrice: 124,
baseVolume: 5_200_000,
},
{
symbol: 'FSLR',
name: 'First Solar',
basePrice: 214,
baseVolume: 2_800_000,
},
],
},
],
},
{
id: 'healthcare',
name: 'Healthcare',
industries: [
{
id: 'pharma',
name: 'Pharmaceuticals',
stocks: [
{ symbol: 'PFE', name: 'Pfizer', basePrice: 31, baseVolume: 36_000_000 },
{ symbol: 'MRK', name: 'Merck', basePrice: 132, baseVolume: 8_700_000 },
{
symbol: 'LLY',
name: 'Eli Lilly',
basePrice: 912,
baseVolume: 3_800_000,
},
],
},
{
id: 'devices',
name: 'Medical Devices',
stocks: [
{ symbol: 'ABT', name: 'Abbott', basePrice: 126, baseVolume: 5_100_000 },
{ symbol: 'SYK', name: 'Stryker', basePrice: 337, baseVolume: 1_700_000 },
{
symbol: 'ISRG',
name: 'Intuitive Surgical',
basePrice: 490,
baseVolume: 1_300_000,
},
],
},
],
},
];
const stockIndexBySymbol = new Map<string, number>();
let runningIndex = 0;
STOCK_TREE.forEach((sector) => {
sector.industries.forEach((industry) => {
industry.stocks.forEach((stock) => {
stockIndexBySymbol.set(stock.symbol, runningIndex);
runningIndex += 1;
});
});
});
const getTick = () => Math.floor(Date.now() / 2_000);
function getLeafMetrics(stock: StockLeaf, tick: number) {
const stockIndex = stockIndexBySymbol.get(stock.symbol) ?? 0;
const drift = Math.sin((tick + stockIndex) * 0.65) * 0.018;
const volumeDrift = Math.cos((tick + stockIndex) * 0.47) * 0.14;
const price =
Math.round(stock.basePrice * (1 + drift) * PRICE_ROUNDING_FACTOR) /
PRICE_ROUNDING_FACTOR;
const volume = Math.round(stock.baseVolume * (1 + volumeDrift));
return { price, volume };
}
function getIndustry(sectorName: string, industryName: string) {
return STOCK_TREE.find((sector) => sector.name === sectorName)?.industries.find(
(industry) => industry.name === industryName,
);
}
function getSectorSummaryRows(tick: number): TreeStockRow[] {
return STOCK_TREE.map((sector) => {
let priceAccumulator = 0;
let volumeAccumulator = 0;
let stockCount = 0;
sector.industries.forEach((industry) => {
industry.stocks.forEach((stock) => {
const metrics = getLeafMetrics(stock, tick);
priceAccumulator += metrics.price;
volumeAccumulator += metrics.volume;
stockCount += 1;
});
});
return {
id: `sector-${sector.id}`,
name: sector.name,
symbol: '',
price:
Math.round((priceAccumulator / stockCount) * PRICE_ROUNDING_FACTOR) /
PRICE_ROUNDING_FACTOR,
volume: volumeAccumulator,
childrenCount: sector.industries.length,
};
});
}
function getIndustryRows(sectorName: string, tick: number): TreeStockRow[] {
const sector = STOCK_TREE.find((candidate) => candidate.name === sectorName);
if (!sector) {
return [];
}
return sector.industries.map((industry) => {
let priceAccumulator = 0;
let volumeAccumulator = 0;
industry.stocks.forEach((stock) => {
const metrics = getLeafMetrics(stock, tick);
priceAccumulator += metrics.price;
volumeAccumulator += metrics.volume;
});
return {
id: `industry-${sector.id}-${industry.id}`,
name: industry.name,
symbol: '',
price:
Math.round(
(priceAccumulator / industry.stocks.length) * PRICE_ROUNDING_FACTOR,
) / PRICE_ROUNDING_FACTOR,
volume: volumeAccumulator,
childrenCount: industry.stocks.length,
};
});
}
function getLeafRows(
sectorName: string,
industryName: string,
tick: number,
): TreeStockRow[] {
const industry = getIndustry(sectorName, industryName);
if (!industry) {
return [];
}
return industry.stocks.map((stock) => {
const metrics = getLeafMetrics(stock, tick);
return {
id: `stock-${stock.symbol}`,
name: stock.name,
symbol: stock.symbol,
price: metrics.price,
volume: metrics.volume,
childrenCount: 0,
};
});
}
function fakeTreeStockServer(
params: GridGetRowsParams,
delayMs: number = 120,
): Promise<GridGetRowsResponse> {
const tick = getTick();
const groupKeys = params.groupKeys ?? [];
if (groupKeys.length === 0) {
const allRows = getSectorSummaryRows(tick);
const page = params.paginationModel?.page ?? 0;
const pageSize = params.paginationModel?.pageSize ?? 5;
const start = page * pageSize;
const paginatedRows = allRows.slice(start, start + pageSize);
return new Promise((resolve) => {
setTimeout(() => {
resolve({
rows: paginatedRows,
rowCount: allRows.length,
});
}, delayMs);
});
}
if (groupKeys.length === 1) {
const rows = getIndustryRows(groupKeys[0], tick);
return new Promise((resolve) => {
setTimeout(() => {
resolve({ rows });
}, delayMs);
});
}
const rows = getLeafRows(groupKeys[0], groupKeys[1], tick);
return new Promise((resolve) => {
setTimeout(() => {
resolve({ rows });
}, delayMs);
});
}
function FlashOnChange({
children,
changeId,
align = 'left',
fontWeight,
}: {
children: React.ReactNode;
changeId: number;
align?: 'left' | 'right';
fontWeight?: React.CSSProperties['fontWeight'];
}) {
const [flash, setFlash] = React.useState(false);
React.useEffect(() => {
if (changeId === 0) {
return undefined;
}
setFlash(true);
const timeout = setTimeout(() => setFlash(false), 500);
return () => clearTimeout(timeout);
}, [changeId]);
return (
<Typography
variant="body2"
sx={[
{
display: 'flex',
alignItems: 'center',
justifyContent: align === 'right' ? 'flex-end' : 'flex-start',
height: '100%',
paddingRight: '10px',
paddingLeft: '10px',
width: '100%',
fontWeight,
},
(theme) => ({
position: 'relative',
width: 'calc(100% + 20px)',
left: '-10px',
transition: 'background-color 500ms ease',
backgroundColor: flash
? alpha(theme.palette.warning.main, 0.22)
: 'transparent',
}),
]}
>
{children}
</Typography>
);
}
const columns: GridColDef<TreeStockRow>[] = [
{
field: 'symbol',
headerName: 'Ticker',
width: 110,
},
{
field: 'price',
headerName: 'Price',
type: 'number',
width: 120,
renderCell: (params: GridRenderCellParams<TreeStockRow, number>) => (
<FlashOnChange
changeId={params.value ?? 0}
align="right"
fontWeight={params.row.childrenCount === 0 ? 'bold' : undefined}
>
${params.value?.toFixed(2)}
</FlashOnChange>
),
},
{
field: 'volume',
headerName: 'Volume',
type: 'number',
width: 150,
renderCell: (params: GridRenderCellParams<TreeStockRow, number>) => (
<FlashOnChange changeId={params.value ?? 0} align="right">
{params.value?.toLocaleString()}
</FlashOnChange>
),
},
];
export default function ServerSideTreeDataRevalidation() {
const dataSource: GridDataSource = React.useMemo(
() => ({
getRows: async (params) => {
const response = await fakeTreeStockServer(params);
return {
rows: response.rows,
rowCount: response.rowCount,
};
},
getGroupKey: (row) => row.name,
getChildrenCount: (row) => row.childrenCount,
}),
[],
);
return (
<div style={{ width: '100%', height: 400 }}>
<DataGridPro
treeData
columns={columns}
dataSource={dataSource}
dataSourceCache={null}
dataSourceRevalidateMs={2_000}
pagination
initialState={{
pagination: { paginationModel: { pageSize: 4, page: 0 }, rowCount: 0 },
}}
pageSizeOptions={[4, 8]}
disableColumnSorting
disableColumnFilter
/>
</div>
);
}
행 확장 상태 유지 (Row expansion state persistence)
행 확장 상태 유지에 대한 자세한 내용은 Server-side data row grouping—Row expansion state persistence 문서를 참고하세요. 구현과 동작은 트리 데이터를 다룰 때도 동일해요.
아래 데모에서 일부 행을 확장하고 두 가지 다른 재페치(refetch) 액션 버튼을 사용해 동작의 차이를 확인해보세요.
import * as React from 'react';
import {
DataGridPro,
useGridApiRef,
GridInitialState,
GridDataSource,
GridGetRowsResponse,
GRID_ROOT_GROUP_ID,
} from '@mui/x-data-grid-pro';
import Button from '@mui/material/Button';
import { useMockServer } from '@mui/x-data-grid-generator';
const pageSizeOptions = [5, 10, 50];
const serverOptions = { useCursorPagination: false };
const dataSetOptions = {
dataSet: 'Employee' as const,
rowLength: 1000,
treeData: { maxDepth: 3, groupingField: 'name', averageChildren: 5 },
};
export default function ServerSideTreeDataExpansionPersistence() {
const apiRef = useGridApiRef();
const { fetchRows, ...props } = useMockServer<GridGetRowsResponse>(
dataSetOptions,
serverOptions,
);
const dataSource: GridDataSource = React.useMemo(
() => ({
getRows: async (params) => {
const urlParams = new URLSearchParams({
paginationModel: JSON.stringify(params.paginationModel),
filterModel: JSON.stringify(params.filterModel),
sortModel: JSON.stringify(params.sortModel),
groupKeys: JSON.stringify(params.groupKeys),
});
const getRowsResponse = await fetchRows(
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
},
getGroupKey: (row) => row[dataSetOptions.treeData.groupingField],
getChildrenCount: (row) => row.descendantCount,
}),
[fetchRows],
);
const initialState: GridInitialState = React.useMemo(
() => ({
...props.initialState,
pagination: {
paginationModel: {
pageSize: 5,
},
rowCount: 0,
},
}),
[props.initialState],
);
return (
<div style={{ width: '100%' }}>
<div style={{ display: 'flex', gap: 8, paddingBottom: 4 }}>
<Button
variant="outlined"
onClick={() => {
apiRef.current?.dataSource.fetchRows();
}}
>
Fetch and keep the children
</Button>
<Button
variant="outlined"
onClick={() => {
apiRef.current?.dataSource.fetchRows(GRID_ROOT_GROUP_ID, {
keepChildrenExpanded: false,
});
}}
>
Fetch and collapse the children
</Button>
</div>
<div style={{ height: 400, position: 'relative' }}>
<DataGridPro
{...props}
treeData
dataSource={dataSource}
dataSourceCache={null}
apiRef={apiRef}
pagination
pageSizeOptions={pageSizeOptions}
initialState={initialState}
/>
</div>
</div>
);
}
오류 처리 (Error handling)
각 행 그룹 확장마다 자식을 가져오기 위해 Data Source가 호출돼요. 페치 중 오류가 발생하면 Data Grid는 행 그룹 셀에 오류 메시지를 표시해요. Server-side data overview—Error handling에 설명된 params를 포함하는 오류 객체로 onDataSourceError()도 트리거돼요.
아래 데모는 요청이 실패할 때 행 그룹 레벨에서 오류 메시지와 알림을 렌더링하는데, 상단의 체크박스와 Refetch rows 버튼으로 이를 시뮬레이션할 수 있어요. 체크박스를 활성화한 상태로 행 그룹을 확장해 이 동작을 확인해보세요. 단순함을 위해 캐싱은 비활성화되어 있어요.
import * as React from 'react';
import {
DataGridPro,
useGridApiRef,
GridInitialState,
GridDataSource,
GridGetRowsResponse,
GridGetRowsError,
} from '@mui/x-data-grid-pro';
import Snackbar from '@mui/material/Snackbar';
import Button from '@mui/material/Button';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import { alpha, styled, darken, lighten } from '@mui/material/styles';
import { useMockServer } from '@mui/x-data-grid-generator';
const pageSizeOptions = [5, 10, 50];
const serverOptions = { useCursorPagination: false };
const dataSetOptions = {
dataSet: 'Employee' as const,
rowLength: 1000,
treeData: { maxDepth: 3, groupingField: 'name', averageChildren: 5 },
};
export default function ServerSideTreeDataErrorHandling() {
const apiRef = useGridApiRef();
const [rootError, setRootError] = React.useState<string>();
const [childrenError, setChildrenError] = React.useState<string>();
const [shouldRequestsFail, setShouldRequestsFail] = React.useState(false);
const { fetchRows, ...props } = useMockServer<GridGetRowsResponse>(
dataSetOptions,
serverOptions,
shouldRequestsFail,
);
const dataSource: GridDataSource = React.useMemo(
() => ({
getRows: async (params) => {
const urlParams = new URLSearchParams({
paginationModel: JSON.stringify(params.paginationModel),
filterModel: JSON.stringify(params.filterModel),
sortModel: JSON.stringify(params.sortModel),
groupKeys: JSON.stringify(params.groupKeys),
});
const getRowsResponse = await fetchRows(
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
},
getGroupKey: (row) => row[dataSetOptions.treeData.groupingField],
getChildrenCount: (row) => row.descendantCount,
}),
[fetchRows],
);
const initialState: GridInitialState = React.useMemo(
() => ({
...props.initialState,
pagination: {
paginationModel: {
pageSize: 5,
},
rowCount: 0,
},
}),
[props.initialState],
);
return (
<div style={{ width: '100%' }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<Button
onClick={() => {
setRootError('');
apiRef.current?.dataSource.fetchRows();
}}
>
Refetch rows
</Button>
<FormControlLabel
control={
<Checkbox
checked={shouldRequestsFail}
onChange={(event) => setShouldRequestsFail(event.target.checked)}
/>
}
label="Make the requests fail"
/>
</div>
<div style={{ height: 400, position: 'relative' }}>
<DataGridPro
{...props}
treeData
dataSource={dataSource}
onDataSourceError={(error) => {
if (error instanceof GridGetRowsError) {
if (!error.params.groupKeys || error.params.groupKeys.length === 0) {
setRootError(error.message);
} else {
setChildrenError(
`${error.message} (Requested level: ${error.params.groupKeys.join(' > ')})`,
);
}
}
}}
dataSourceCache={null}
apiRef={apiRef}
pagination
pageSizeOptions={pageSizeOptions}
initialState={initialState}
/>
{rootError && <ErrorOverlay error={rootError} />}
<Snackbar
open={!!childrenError}
autoHideDuration={3000}
onClose={() => setChildrenError('')}
message={childrenError}
/>
</div>
</div>
);
}
const StyledDiv = styled('div')(({ theme: t }) => ({
position: 'absolute',
zIndex: 10,
fontSize: '0.875em',
top: 0,
height: '100%',
width: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: '4px',
border: `1px solid ${lighten(alpha(t.palette.divider, 1), 0.88)}`,
backgroundColor: t.palette.background.default,
...t.applyStyles('dark', {
borderColor: darken(alpha(t.palette.divider, 1), 0.68),
}),
}));
function ErrorOverlay({ error }: { error: string }) {
if (!error) {
return null;
}
return <StyledDiv>{error}</StyledDiv>;
}
그룹 확장 (Group expansion)
서버 쪽 트리 데이터의 그룹 확장은 client-side row grouping documentation에 설명된 것과 유사하게 동작해요. 차이점은 데이터가 처음에는 사용할 수 없으며, defaultGroupingExpansionDepth와 isGroupExpandedByDefault() props를 기반으로 Data Grid가 마운트된 후 워터폴 방식으로 자동으로 페치된다는 점이에요.
다음 데모는 defaultGroupingExpansionDepth={-1}을 사용해 기본적으로 트리의 모든 레벨을 확장해요.
import * as React from 'react';
import {
DataGridPro,
useGridApiRef,
GridInitialState,
GridDataSource,
} from '@mui/x-data-grid-pro';
import Button from '@mui/material/Button';
import { useMockServer } from '@mui/x-data-grid-generator';
type DataSet = 'Commodity' | 'Employee';
const pageSizeOptions = [5, 10, 50];
const dataSetOptions = {
dataSet: 'Employee' as DataSet,
rowLength: 1000,
treeData: { maxDepth: 3, groupingField: 'name', averageChildren: 5 },
};
export default function ServerSideTreeDataGroupExpansion() {
const apiRef = useGridApiRef();
const { fetchRows, columns, initialState } = useMockServer(dataSetOptions);
const dataSource: GridDataSource = React.useMemo(
() => ({
getRows: async (params) => {
const urlParams = new URLSearchParams({
paginationModel: JSON.stringify(params.paginationModel),
filterModel: JSON.stringify(params.filterModel),
sortModel: JSON.stringify(params.sortModel),
groupKeys: JSON.stringify(params.groupKeys),
});
const getRowsResponse = await fetchRows(
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
},
getGroupKey: (row) => row[dataSetOptions.treeData.groupingField],
getChildrenCount: (row) => row.descendantCount,
}),
[fetchRows],
);
const initialStateWithPagination: GridInitialState = React.useMemo(
() => ({
...initialState,
pagination: {
paginationModel: {
pageSize: 5,
},
rowCount: 0,
},
}),
[initialState],
);
return (
<div style={{ width: '100%' }}>
<Button onClick={() => apiRef.current?.dataSource.cache.clear()}>
Reset cache
</Button>
<div style={{ height: 400 }}>
<DataGridPro
columns={columns}
dataSource={dataSource}
treeData
apiRef={apiRef}
pagination
pageSizeOptions={pageSizeOptions}
initialState={initialStateWithPagination}
showToolbar
defaultGroupingExpansionDepth={-1}
/>
</div>
</div>
);
}
커스텀 캐시 (Custom cache)
Data Source는 기본적으로 페치된 데이터를 저장하는 자체 내장 캐시를 사용해요. 필요한 경우 dataSourceCache prop을 사용해 커스텀 캐시를 제공할 수 있어요. 자세한 내용은 Server-side data overview—Data caching 문서를 참고하세요.
다음 데모는 @tanstack/react-core의 QueryClient를 Data Source 캐시로 사용해요.
import * as React from 'react';
import {
DataGridPro,
useGridApiRef,
GridInitialState,
GridDataSourceCache,
GridDataSource,
GridGetRowsParams,
} from '@mui/x-data-grid-pro';
import Button from '@mui/material/Button';
import { useMockServer } from '@mui/x-data-grid-generator';
import { QueryClient } from '@tanstack/query-core';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 60,
},
},
});
function getKey(params: GridGetRowsParams) {
return [
params.paginationModel,
params.sortModel,
params.filterModel,
params.groupKeys,
];
}
const cache: GridDataSourceCache = {
set: (key: GridGetRowsParams, value) => {
const queryKey = getKey(key);
queryClient.setQueryData(queryKey, value);
},
get: (key: GridGetRowsParams) => {
const queryKey = getKey(key);
return queryClient.getQueryData(queryKey);
},
clear: () => {
queryClient.clear();
},
};
const pageSizeOptions = [5, 10, 50];
const dataSetOptions = {
dataSet: 'Employee' as const,
rowLength: 1000,
treeData: { maxDepth: 3, groupingField: 'name', averageChildren: 5 },
};
export default function ServerSideTreeDataCustomCache() {
const apiRef = useGridApiRef();
const { fetchRows, ...props } = useMockServer(dataSetOptions);
const dataSource: GridDataSource = React.useMemo(
() => ({
getRows: async (params) => {
const urlParams = new URLSearchParams({
paginationModel: JSON.stringify(params.paginationModel),
filterModel: JSON.stringify(params.filterModel),
sortModel: JSON.stringify(params.sortModel),
groupKeys: JSON.stringify(params.groupKeys),
});
const getRowsResponse = await fetchRows(
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
},
getGroupKey: (row) => row[dataSetOptions.treeData.groupingField],
getChildrenCount: (row) => row.descendantCount,
}),
[fetchRows],
);
const initialState: GridInitialState = React.useMemo(
() => ({
...props.initialState,
pagination: {
paginationModel: {
pageSize: 5,
},
rowCount: 0,
},
}),
[props.initialState],
);
return (
<div style={{ width: '100%' }}>
<Button onClick={() => queryClient.clear()}>Reset cache</Button>
<div style={{ height: 400 }}>
<DataGridPro
{...props}
dataSource={dataSource}
dataSourceCache={cache}
treeData
apiRef={apiRef}
pagination
pageSizeOptions={pageSizeOptions}
initialState={initialState}
showToolbar
/>
</div>
</div>
);
}