본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Data Grid - 서버 측 데이터 레시피

원문 보기 위키 갱신

Data Grid - 서버 측 데이터 레시피 (Server-side data recipes)

고급 데이터 소스 사용 사례를 위한 레시피예요.

출처: MUI X documentation

본문

커서 기반 페이지네이션 (Cursor-based pagination)

커서 기반 페이지네이션은 다음 페이지를 가져오려면 이전 페이지 응답의 커서가 필요해요. 오프셋(offset) 페이지네이션이 독립적으로 어떤 페이지로든 점프할 수 있는 것과 달리, 각 페이지 요청은 이전 응답에서 반환된 커서에 의존해요.

구현 방법에는 두 가지가 있어요:

  1. 차단(Blocking) 방식: 사용자는 현재 응답이 커서와 함께 도착한 후에만 다음 페이지로 이동할 수 있어요
  2. 비차단(Non-blocking) 방식: 사용자가 즉시 다음을 클릭할 수 있게 하되, 이전 커서를 사용할 수 있을 때까지 요청을 큐에 대기시켜요

차단 방식 (Blocking approach)

다음 예제는 paginationModel 상태를 제어해 차단 방식을 보여줘요. 이전 페이지의 응답이 도착할 때만 업데이트되므로, 커서가 항상 다음 요청에 사용 가능함을 보장해요.

import * as React from 'react';
import {
  DataGrid,
  GridDataSource,
  GridPaginationModel,
  GridRowId,
} from '@mui/x-data-grid';
import { useMockServer } from '@mui/x-data-grid-generator';

export default function ServerSideCursorBlocking() {
  const { columns, initialState, fetchRows } = useMockServer(
    {},
    { useCursorPagination: true, minDelay: 1000, maxDelay: 2000 },
  );
  const [paginationModel, setPaginationModel] = React.useState({
    page: 0,
    pageSize: 10,
  });
  const paginationModelRef = React.useRef(paginationModel);
  paginationModelRef.current = paginationModel;

  const mapPageToNextCursor = React.useRef<{
    [page: number]: GridRowId | undefined;
  }>({});

  const handlePaginationModelChange = (newPaginationModel: GridPaginationModel) => {
    if (
      newPaginationModel.page === 0 ||
      mapPageToNextCursor.current[newPaginationModel.page - 1]
    ) {
      setPaginationModel(newPaginationModel);
    }
  };

  const dataSource: GridDataSource = React.useMemo(
    () => ({
      getRows: async (params) => {
        const cursor =
          mapPageToNextCursor.current[paginationModelRef.current.page - 1];
        const urlParams = new URLSearchParams({
          paginationModel: JSON.stringify(params.paginationModel),
          filterModel: JSON.stringify(params.filterModel),
          sortModel: JSON.stringify(params.sortModel),
          cursor: String(cursor ?? ''),
        });
        const getRowsResponse = await fetchRows(
          `https://mui.com/x/api/data-grid?${urlParams.toString()}`,
        );
        mapPageToNextCursor.current[params.paginationModel?.page || 0] =
          getRowsResponse.pageInfo?.nextCursor;
        return {
          rows: getRowsResponse.rows,
          rowCount: getRowsResponse.rowCount,
        };
      },
    }),
    [fetchRows],
  );

  return (
    <div style={{ width: '100%', height: 400 }}>
      <DataGrid
        columns={columns}
        dataSource={dataSource}
        pagination
        initialState={{
          ...initialState,
          pagination: { rowCount: 0 },
        }}
        paginationModel={paginationModel}
        onPaginationModelChange={handlePaginationModelChange}
        pageSizeOptions={[10, 20, 50]}
      />
    </div>
  );
}

비차단 방식 (Non-blocking approach)

다음 예제는 두 가지 핵심 메서드가 있는 커스텀 캐시를 사용해 비차단 방식을 보여줘요:

  • pushKey(): 응답이 도착하기 전에 요청 순서를 추적해 즉시 페이지네이션을 가능하게 해요
  • getLast(): 실제 요청을 하기 전에 이전 페이지의 커서가 해석되기를 기다려요

캐시는 데이터 일관성을 보장하기 위해 필터나 정렬 모델이 바뀔 때마다 비워져요.

오류 처리의 경우, 예제는 8페이지를 요청할 때 서버 오류를 시뮬레이션해요. 오류가 발생하면 해당 요청의 캐시 항목이 삭제되고, 일관된 상태를 유지하기 위해 paginationModel이 이전 페이지로 되돌아가요.

import * as React from 'react';
import {
  DataGrid,
  GridDataSource,
  GridGetRowsParams,
  GridGetRowsResponse,
  useGridApiRef,
} from '@mui/x-data-grid';
import Snackbar from '@mui/material/Snackbar';
import Alert, { AlertProps } from '@mui/material/Alert';
import { useMockServer } from '@mui/x-data-grid-generator';

function getKeyDefault(params: GridGetRowsParams) {
  return JSON.stringify([
    params.filterModel,
    params.sortModel,
    params.start,
    params.end,
  ]);
}

class Cache {
  private cache: Record<string, { value: GridGetRowsResponse }>;

  private cacheKeys: Set<string>;

  private getKey: (params: GridGetRowsParams) => string;

  constructor() {
    this.cache = {};
    this.cacheKeys = new Set();
    this.getKey = getKeyDefault;
  }

  set(key: GridGetRowsParams, value: GridGetRowsResponse) {
    const keyString = this.getKey(key);
    this.cache[keyString] = { value };
  }

  get(key: GridGetRowsParams): GridGetRowsResponse | undefined {
    const keyString = this.getKey(key);
    const entry = this.cache[keyString];
    if (!entry) {
      return undefined;
    }

    return entry.value;
  }

  pushKey(key: GridGetRowsParams) {
    const keyString = this.getKey(key);
    this.cacheKeys.add(keyString);
  }

  deleteKey(key: GridGetRowsParams) {
    const keyString = this.getKey(key);
    delete this.cache[keyString];
    this.cacheKeys.delete(keyString);
  }

  async getLast(key: GridGetRowsParams): Promise<GridGetRowsResponse | undefined> {
    const cacheKeys = Array.from(this.cacheKeys);
    const prevKey = cacheKeys[cacheKeys.indexOf(this.getKey(key)) - 1];
    if (!prevKey) {
      return undefined;
    }
    if (this.cache[prevKey]) {
      return this.cache[prevKey].value;
    }
    return new Promise((resolve) => {
      const intervalId = setInterval(() => {
        if (this.cache[prevKey]) {
          clearInterval(intervalId);
          resolve(this.cache[prevKey].value);
        }
      }, 100);
    });
  }

  clear() {
    this.cache = {};
    this.cacheKeys.clear();
  }
}

export default function ServerSideCursorNonBlocking() {
  const apiRef = useGridApiRef();
  const [snackbar, setSnackbar] = React.useState<AlertProps | null>(null);
  const { columns, initialState, fetchRows } = useMockServer(
    {},
    { useCursorPagination: true, minDelay: 200, maxDelay: 500 },
  );
  const cache = React.useMemo(() => new Cache(), []);

  const dataSource: GridDataSource = React.useMemo(
    () => ({
      getRows: async (params) => {
        cache.pushKey(params);
        const latestResponse = await cache.getLast(params);
        const urlParams = new URLSearchParams({
          paginationModel: JSON.stringify(params.paginationModel),
          filterModel: JSON.stringify(params.filterModel),
          sortModel: JSON.stringify(params.sortModel),
          cursor: String(latestResponse?.pageInfo?.nextCursor ?? ''),
        });
        try {
          if (params.paginationModel?.page === 7) {
            throw new Error('Simulate server error on page 8');
          }
          const getRowsResponse = await fetchRows(
            `https://mui.com/x/api/data-grid?${urlParams.toString()}`,
          );
          return {
            rows: getRowsResponse.rows,
            rowCount: getRowsResponse.rowCount,
            pageInfo: { nextCursor: getRowsResponse.pageInfo?.nextCursor },
          };
        } catch (error) {
          cache.deleteKey(params);
          apiRef.current?.setPaginationModel({
            page: params.paginationModel!.page - 1,
            pageSize: params.paginationModel!.pageSize,
          });
          setSnackbar({ children: (error as Error).message, severity: 'error' });
          throw error;
        }
      },
    }),
    [fetchRows, cache, apiRef],
  );

  const handleCloseSnackbar = () => {
    setSnackbar(null);
  };

  return (
    <div style={{ width: '100%', height: 400 }}>
      <DataGrid
        apiRef={apiRef}
        columns={columns}
        dataSource={dataSource}
        dataSourceCache={cache}
        pagination
        initialState={{
          ...initialState,
          pagination: {
            paginationModel: {
              page: 0,
              pageSize: 10,
            },
            rowCount: 0,
          },
        }}
        pageSizeOptions={[10, 20, 50]}
        onFilterModelChange={() => cache.clear()}
        onSortModelChange={() => cache.clear()}
      />
      {!!snackbar && (
        <Snackbar
          open
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
          onClose={handleCloseSnackbar}
          autoHideDuration={6000}
        >
          <Alert {...snackbar} onClose={handleCloseSnackbar} />
        </Snackbar>
      )}
    </div>
  );
}

트리 데이터 중첩 페이지네이션 (Tree data nested pagination)

기본적으로 페이지네이션은 트리의 첫 번째 수준에서만 작동해요. 다음 데모처럼 행 고정 기능으로 중첩 페이지네이션을 만들 수 있어요.

:::warning

이 데모는 행 고정을 사용해 중첩 지연 로딩을 구현하므로, 캐싱, 행 선택, 복사&붙여넣기 같은 일부 기능이 예상대로 작동하지 않을 수 있어요.

내부 구현에 대한 업데이트는 Server-side data—Nested lazy loading 섹션을 확인하세요.

:::

import * as React from 'react';
import {
  DataGridPro,
  useGridApiRef,
  type GridDataSource,
} from '@mui/x-data-grid-pro';
import { useMockServer } from '@mui/x-data-grid-generator';
import useNestedPagination from './useNestedPagination';

const pageSizeOptions = [5, 10, 50];
const dataSetOptions = {
  dataSet: 'Employee' as const,
  rowLength: 1000,
  treeData: { maxDepth: 3, groupingField: 'name', averageChildren: 20 },
};
const serverOptions = {};

const initialPaginationModel = {
  pageSize: 5,
  page: 0,
};

export default function ServerSideTreeDataNestedPagination() {
  const apiRef = useGridApiRef();

  const { groupKeys, ...props } = useNestedPagination(initialPaginationModel);
  const { fetchRows, columns, initialState } = useMockServer(
    dataSetOptions,
    serverOptions,
    false,
    true,
  );

  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(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, groupKeys],
  );

  return (
    <div style={{ width: '100%', height: 500 }}>
      <DataGridPro
        {...props}
        columns={columns}
        dataSource={dataSource}
        dataSourceCache={null}
        treeData
        apiRef={apiRef}
        pagination
        pageSizeOptions={pageSizeOptions}
        initialState={initialState}
        showToolbar
      />
    </div>
  );
}

더 알아보기 (Learn more)