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

Data Grid - 서버 사이드 데이터

원문 보기 위키 갱신

Data Source 레이어를 사용해서 Data Grid에서 서버 사이드 데이터를 다루는 방법을 알아봐요.

출처: MUI X documentation

본문

소개 (Introduction)

React에서 서버 사이드 데이터 관리는 데이터셋이 커질수록 복잡해질 수 있어요. 수동 데이터 가져오기, 페이지네이션, 정렬, 필터링, 성능 최적화 같은 것들이 도전 과제가 되죠. 전용 모듈이 이런 복잡성을 추상화해서 개발자 경험을 개선할 수 있어요. Data Grid는 이를 위해 Data Source 레이어를 제공해요.

:::success 예제로 배우는 걸 선호한다면, 서버 사이드 데이터 튜토리얼이 풀스택 앱에서 Data Source 레이어를 구현하는 방법을 보여 줘요. :::

문제: 복잡성이 쌓여감

사용자 목록을 표시하고 페이지네이션, 컬럼 헤더 정렬, 필터링을 지원하는 Data Grid를 생각해 보세요. 사용자가 페이지를 바꾸거나 필터링·정렬을 업데이트하면 Data Grid는 서버에서 데이터를 가져와요. 그런 모습이 어쩌면 이렇겠죠.

const [rows, setRows] = React.useState([]);
const [paginationModel, setPaginationModel] = React.useState({
  page: 0,
  pageSize: 10,
});
const [filterModel, setFilterModel] = React.useState({ items: [] });
const [sortModel, setSortModel] = React.useState([]);

React.useEffect(() => {
  const fetcher = async () => {
    // fetch data from server
    const data = await fetch('https://my-api.com/data', {
      method: 'GET',
      body: JSON.stringify({
        page: paginationModel.page,
        pageSize: paginationModel.pageSize,
        sortModel,
        filterModel,
      }),
    });
    setRows(data.rows);
  };
  fetcher();
}, [paginationModel, sortModel, filterModel]);

<DataGrid
  columns={columns}
  pagination
  sortingMode="server"
  filterMode="server"
  paginationMode="server"
  onPaginationModelChange={setPaginationModel}
  onSortModelChange={setSortModel}
  onFilterModelChange={setFilterModel}
/>;

하지만 이 예시는 Data Grid에서 서버 사이드 데이터를 다룰 때의 복잡성의 표면만 긁은 것뿐이에요—다음 기능들은 여전히 다뤄지지 않았어요.

  • 성능 최적화
  • 데이터 캐싱과 요청 중복 제거(deduping)
  • 행 그룹화와 트리 데이터
  • 지연 로딩(lazy-loading) 데이터
  • 데이터 업데이트 처리(행 편집과 삭제)
  • 필요에 따른 데이터 재가져오기

이런 각 기능을 개별적으로 해결하려 하면 코드가 지나치게 복잡해지고 유지보수하기 어려워질 수 있어요.

해결책: Data Source 레이어

Data Grid에서 위 상황의 해결책은 Data Source라는 중앙 집중 추상화 레이어예요. 이 레이어는 클라이언트의 Data Grid와 서버의 실제 데이터 사이의 통신을 위한 인터페이스를 제공해요.

Data Source에는 반드시 구현해야 할 초기 필수 메서드 집합이 있어요. Data Grid는 내부적으로 이 메서드들을 사용해서 필요할 때 데이터의 일부분을 가져와요.

다음 코드 스니펫은 최소 GridDataSource 인터페이스 구성을 보여 줘요. getChildrenCount()나 getGroupKey() 같은 속성이 있는 더 복잡한 구현들은 이 소개 페이지에 이어지는 특정 서버 사이드 기능 문서들에서 다룬답니다.

interface GridDataSource {
  /**
   * This method is called when the grid needs to fetch rows.
   * @param {GridGetRowsParams} params The parameters required to fetch the rows.
   * @returns {Promise<GridGetRowsResponse>} A promise that resolves to the data of
   * type [GridGetRowsResponse].
   */
  getRows(params: GridGetRowsParams): Promise<GridGetRowsResponse>;
}

앞서 언급한 문제의 컴포넌트를 Data Source로 구현하면 이렇게 생겼어요.

const customDataSource: GridDataSource = {
  getRows: async (params: GridGetRowsParams): GetRowsResponse => {
    const response = await fetch('https://my-api.com/data', {
      method: 'GET',
      body: JSON.stringify(params),
    });
    const data = await response.json();

    return {
      rows: data.rows,
      rowCount: data.totalCount,
    };
  },
}

<DataGrid
  columns={columns}
  dataSource={customDataSource}
  pagination
/>

Data Source를 사용하면 전체 코드 양이 크게 줄어들어요. 제어 상태(controlled states)를 관리할 필요도 없고, 데이터 가져오기 로직도 중앙 집중화돼요.

서버 사이드 필터링, 정렬, 페이지네이션

Data Source는 필터링·정렬·페이지네이션 같은 기존 서버 사이드 기능의 동작 방식을 바꿔요.

Data Source 없이(기본 동작)

Data Source가 구현되어 있지 않으면 필터링·정렬·페이지네이션 같은 기능은 기본적으로 클라이언트 사이드에서 동작하도록 설계돼요.

서버 사이드 데이터와 올바르게 동작하려면 이 기능들을 명시적으로 "server" 모드로 설정하고, 아래와 같이 업데이트된 변수를 기반으로 서버에서 데이터를 가져오는 onFilterModelChange(), onSortModelChange(), onPaginationModelChange() 이벤트 핸들러를 제공해야 해요.

<DataGrid
  columns={columns}
  rows={rows}
  pagination
  sortingMode="server"
  filterMode="server"
  paginationMode="server"
  onPaginationModelChange={(newPaginationModel) => {
    // fetch data from server
  }}
  onSortModelChange={(newSortModel) => {
    // fetch data from server
  }}
  onFilterModelChange={(newFilterModel) => {
    // fetch data from server
  }}
/>

Data Source와 함께

Data Source가 구현되어 있으면 필터링·정렬·페이지네이션 같은 기능은 자동으로 "server" 모드로 설정돼요. 관련 모델이 업데이트되면 Data Grid는 GridGetRowsParams 타입의 업데이트된 값으로 getRows() 메서드를 호출해서 업데이트된 데이터를 가져와요.

<DataGrid
  columns={columns}
  // automatically sets `sortingMode="server"`, `filterMode="server"`, `paginationMode="server"`
  dataSource={customDataSource}
/>

다음 데모가 이 동작을 보여 줘요.

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

export default function ServerSideDataGrid() {
  const { columns, initialState, fetchRows } = useMockServer(
    {},
    { useCursorPagination: false },
  );

  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),
        });
        const getRowsResponse = await fetchRows(
          `https://mui.com/x/api/data-grid?${urlParams.toString()}`,
        );
        return {
          rows: getRowsResponse.rows,
          rowCount: getRowsResponse.rowCount,
        };
      },
    }),
    [fetchRows],
  );

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

:::info Data Source 데모는 서버 사이드 데이터 가져오기를 시뮬레이션하기 위해 useMockServer() 유틸리티 함수를 사용해요. 실전에서는 이 함수를 자체 서버 사이드 데이터 가져오기 로직으로 교체하면 돼요.

브라우저 콘솔의 Info 섹션을 열면 이루어지는 요청과 응답으로 가져오는 데이터를 볼 수 있어요. :::

이전 데이터를 유지하며 가져오기

기본적으로 Data Grid는 페이지네이션·정렬·필터링 변경 후 새 데이터를 가져오는 동안 표시된 행을 지우고 로딩 오버레이를 보여 줘요. dataSourceKeepPreviousData prop을 전달하면 다음 응답이 올 때까지 이전에 표시된 행을 그대로 둘 수 있어요. 로딩 오버레이는 이전 행 위에 렌더링되므로 페이지 사이에서 그리드 높이가 무너지는 것을 막아 줘요.

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

export default function ServerSideDataGridKeepPreviousData() {
  const { columns, initialState, fetchRows } = useMockServer(
    {},
    { useCursorPagination: false, minDelay: 500, maxDelay: 1500 },
  );

  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),
        });
        const getRowsResponse = await fetchRows(
          `https://mui.com/x/api/data-grid?${urlParams.toString()}`,
        );
        return {
          rows: getRowsResponse.rows,
          rowCount: getRowsResponse.rowCount,
        };
      },
    }),
    [fetchRows],
  );

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

요청이 실패하면 이전 행은 리셋돼요. 이미 실패한 요청을 반영하고 있는 페이지네이션·정렬·필터링 컨트롤과 더 이상 일치하지 않기 때문이에요. 오류는 onDataSourceError 콜백으로 처리하세요.

:::warning dataSourceKeepPreviousData는 플랫 데이터에만 적용돼요. 트리 데이터와 행 그룹화에서는 Data Grid가 재가져오기 때 항상 행을 리셋해요—그렇지 않으면 기존 트리가 새 응답 위에 병합되어 행이 오래된 순서로 렌더링될 수 있기 때문이에요(#21619). :::

데이터 캐싱

Data Source는 가져온 데이터를 기본적으로 캐시해요. 즉, 사용자가 이미 가져온 페이지나 노드를 탐색하면 Grid는 서버에 불필요한 호출을 피하려고 getRows() 함수를 다시 호출하지 않아요.

기본적으로 Grid는 데이터를 평범한 객체에 저장하는 간단한 인메모리 캐시인 GridDataSourceCacheDefault를 사용해요. 이것이 동작하는 모습은 위의 Data Source 데모에서 볼 수 있어요.

캐시 적중률 높이기

캐시 적중률을 높이기 위해 Data Grid는 getRows() 결과를 캐시에 저장하기 전에 청크(chunk)로 나눠요. 그 뒤의 요청에서는 필요에 따라 청크를 조합해서 응답을 재구성해요. 즉, 단일 요청이 GridDataSourceCache의 get() 또는 set() 메서드를 여러 번 호출할 수 있다는 뜻이에요.

청크 크기는 paginationModel의 pageSize 값과 pageSizeOptions props를 기반으로 요청당 예상되는 최저 레코드 수예요. 그 결과 pageSizeOptions prop의 값들이 캐시 적중률에 중요한 역할을 해요. 가장 낮은 값의 배수인 값을 사용하는 것이 좋으며, 각 후속 값이 이전 값의 배수라면 더 좋아요.

몇 가지 예를 들어 볼게요.

  • 최상의 시나리오 – pageSizeOptions={[5, 10, 50, 100]}

    이 경우 청크 크기는 5예요. 즉 pageSize={100}이면 20개의 캐시 레코드가 저장돼요. 처음 100개 레코드까지의 다른 어떤 pageSize에 대한 데이터를 가져와도 전체 데이터셋이 기존 청크로 구성될 수 있으므로 캐시 적중이 돼요.

  • 일부 데이터 누락 – pageSizeOptions={[10, 20, 50]}

    pageSize={50}으로 첫 페이지를 로드하면 5개의 캐시 레코드가 생겨요. 이것은 pageSize={10}에서는 잘 동작하지만 pageSize={20}에서는 잘 동작하지 않아요. pageSize={20}으로 세 번째 페이지를 로드하면 데이터 절반이 이미 캐시에 있음에도 새 요청이 이루어져요.

  • 호환되지 않는 페이지 크기 – pageSizeOptions={[7, 15, 40]}

    이 상황에서 청크 크기는 7이에요. pageSize={15}로 첫 페이지를 가져오면 [7, 7, 1] 레코드로 나뉜 청크가 생겨요. 두 번째 페이지를 로드하면 세 개의 새 청크(역시 [7, 7, 1])가 생기지만, 이제 첫 요청의 세 번째 청크는 두 번째 요청의 첫 청크와 1개 레코드가 겹쳐요. 이 1개 레코드 청크는 pageSize={15} 요청의 마지막 조각으로만 쓰일 수 있고 다른 경우에는 쓸모없어요.

위 예들에서 sortModel과 filterModel은 그대로 유지돼요. 이것들을 바꾸면 새 응답을 가져와 청크에 저장해야 해요.

캐시 수명 커스터마이징

GridDataSourceCacheDefault는 기본 수명(TTL)이 5분이에요. 이것을 커스터마이징하려면 GridDataSourceCacheDefault 생성자에 숫자 값(밀리초)의 ttl 옵션을 전달한 다음, 그걸 dataSourceCache prop에 전달하세요.

import { GridDataSourceCacheDefault } from '@mui/x-data-grid';

const lowTTLCache = new GridDataSourceCacheDefault({ ttl: 1000 * 10 }); // 10 seconds

<DataGrid
  columns={columns}
  dataSource={customDataSource}
  dataSourceCache={lowTTLCache}
/>;
import * as React from 'react';
import {
  DataGrid,
  GridDataSource,
  GridDataSourceCacheDefault,
} from '@mui/x-data-grid';
import { useMockServer } from '@mui/x-data-grid-generator';

const lowTTLCache = new GridDataSourceCacheDefault({ ttl: 1000 * 10 }); // 10 seconds

export default function ServerSideDataGridTTL() {
  const { columns, initialState, fetchRows } = useMockServer(
    {},
    { useCursorPagination: false },
  );

  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),
        });
        const getRowsResponse = await fetchRows(
          `https://mui.com/x/api/data-grid?${urlParams.toString()}`,
        );
        return {
          rows: getRowsResponse.rows,
          rowCount: getRowsResponse.rowCount,
        };
      },
    }),
    [fetchRows],
  );

  const initialStateWithPagination = React.useMemo(
    () => ({
      ...initialState,
      pagination: {
        paginationModel: { pageSize: 10, page: 0 },
        rowCount: 0,
      },
    }),
    [initialState],
  );

  return (
    <div style={{ width: '100%', height: 400 }}>
      <DataGrid
        columns={columns}
        dataSource={dataSource}
        dataSourceCache={lowTTLCache}
        pagination
        initialState={initialStateWithPagination}
        pageSizeOptions={[10, 20, 50]}
      />
    </div>
  );
}

커스텀 캐시 만들기

dataSourceCache prop을 사용해서 처음부터 작성하거나 타사 캐시 라이브러리를 기반으로 한 커스텀 캐시를 제공할 수 있어요. 이 prop은 GridDataSourceCache 타입의 제네릭 인터페이스를 받아요.

export interface GridDataSourceCache {
  set: (key: GridGetRowsParams, value: GridGetRowsResponse) => void;
  get: (key: GridGetRowsParams) => GridGetRowsResponse | undefined;
  clear: () => void;
}

캐싱 비활성화하기

Data Source 캐시를 비활성화하려면 dataSourceCache prop에 null을 전달하세요.

<DataGrid columns={columns} dataSource={customDataSource} dataSourceCache={null} />
import * as React from 'react';
import { DataGrid, GridDataSource } from '@mui/x-data-grid';
import { useMockServer } from '@mui/x-data-grid-generator';

const pageSizeOptions = [5, 10, 50];

const serverOptions = { useCursorPagination: false };
const dataSetOptions = {};

export default function ServerSideDataGridNoCache() {
  const { fetchRows, columns, initialState } = useMockServer(
    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),
        });
        const getRowsResponse = await fetchRows(
          `https://mui.com/x/api/data-grid?${urlParams.toString()}`,
        );
        return {
          rows: getRowsResponse.rows,
          rowCount: getRowsResponse.rowCount,
        };
      },
    }),
    [fetchRows],
  );

  const initialStateWithPagination = React.useMemo(
    () => ({
      ...initialState,
      pagination: {
        paginationModel: { pageSize: 10, page: 0 },
        rowCount: 0,
      },
    }),
    [initialState],
  );

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        initialState={initialStateWithPagination}
        columns={columns}
        dataSource={dataSource}
        dataSourceCache={null}
        pagination
        pageSizeOptions={pageSizeOptions}
      />
    </div>
  );
}

:::success 캐시를 우회하고 dataSource.fetchRows() API 메서드 한 번 호출로 서버에서 행을 강제로 다시 가져오려면 fetch 옵션에 skipCache 플래그를 전달하세요.

apiRef.current.dataSource.fetchRows(GRID_ROOT_GROUP_ID, { skipCache: true });

응답은 캐시를 갱신하는 데 사용돼요. :::

동적 데이터 업데이트 처리하기

동적 서버 사이드 데이터의 새 값을 계속 가져오려면 dataSourceRevalidateMs prop을 사용하세요. 이것은 백그라운드에서 현재 서버 사이드 쿼리를 재검증하고 Data Grid를 최신 데이터로 업데이트하는 폴링 타이머를 시작해요.

아래 데모는 dataSourceRevalidateMs="2_000"을 사용하고 주기적인 업데이트가 보이도록 캐시를 비활성화해요.

import * as React from 'react';
import {
  DataGrid,
  GridColDef,
  GridDataSource,
  GridGetRowsParams,
  GridRenderCellParams,
} from '@mui/x-data-grid';
import Typography from '@mui/material/Typography';
import { alpha } from '@mui/material/styles';
import { Chance } from 'chance';

const chance = new Chance(42);

interface StockRow {
  id: number;
  symbol: string;
  company: string;
  price: number;
  volume: number;
}

const STOCKS = [
  { symbol: 'AAPL', company: 'Apple' },
  { symbol: 'MSFT', company: 'Microsoft' },
  { symbol: 'GOOGL', company: 'Alphabet' },
  { symbol: 'AMZN', company: 'Amazon' },
  { symbol: 'NVDA', company: 'NVIDIA' },
  { symbol: 'META', company: 'Meta' },
  { symbol: 'TSLA', company: 'Tesla' },
  { symbol: 'JPM', company: 'JPMorgan' },
  { symbol: 'V', company: 'Visa' },
  { symbol: 'NFLX', company: 'Netflix' },
];

const ROW_COUNT = 40;

const basePrices: Record<string, number> = {};
STOCKS.forEach((stock, index) => {
  basePrices[stock.symbol] = 60 + ((index * 113 + 17) % 300);
});

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: fontWeight === 'bold' ? 'bold' : undefined,
        },
        (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<StockRow>[] = [
  { field: 'symbol', headerName: 'Symbol', width: 100 },
  {
    field: 'company',
    headerName: 'Company',
    flex: 1,
    minWidth: 160,
    rowHeader: true,
  },
  {
    field: 'price',
    headerName: 'Price',
    type: 'number',
    width: 120,
    renderCell: (params: GridRenderCellParams<StockRow, number>) => (
      <FlashOnChange changeId={params.value ?? 0} align="right" fontWeight="bold">
        ${params.value?.toFixed(2)}
      </FlashOnChange>
    ),
  },
  {
    field: 'volume',
    headerName: 'Volume',
    type: 'number',
    width: 130,
    renderCell: (params: GridRenderCellParams<StockRow, number>) => (
      <FlashOnChange changeId={params.value ?? 0} align="right">
        {params.value?.toLocaleString()}
      </FlashOnChange>
    ),
  },
];

function fakeStockServer(params: GridGetRowsParams) {
  const page = params.paginationModel?.page ?? 0;
  const pageSize = params.paginationModel?.pageSize ?? 5;
  const start = page * pageSize;
  const end = Math.min(start + pageSize, ROW_COUNT);

  const rows: StockRow[] = [];
  for (let index = start; index < end; index += 1) {
    const stock = STOCKS[index % STOCKS.length];
    const basePrice = basePrices[stock.symbol];
    const priceFluctuation = 1 + chance.floating({ min: -0.5, max: 0.5 }) * 0.03;

    rows.push({
      id: index,
      symbol: stock.symbol,
      company: stock.company,
      price: Math.round(basePrice * priceFluctuation * 100) / 100,
      volume: Math.floor(chance.floating({ min: 500_000, max: 20_500_000 })),
    });
  }

  return new Promise<{ rows: StockRow[]; rowCount: number }>((resolve) => {
    setTimeout(() => {
      resolve({
        rows,
        rowCount: ROW_COUNT,
      });
    }, 120);
  });
}

export default function ServerSideDataGridRevalidation() {
  const dataSource: GridDataSource = React.useMemo(
    () => ({
      getRows: async (params: GridGetRowsParams) => {
        const response = await fakeStockServer(params);

        return {
          rows: response.rows,
          rowCount: response.rowCount,
        };
      },
    }),
    [],
  );

  return (
    <div style={{ width: '100%', height: 360 }}>
      <DataGrid
        columns={columns}
        dataSource={dataSource}
        dataSourceCache={null}
        dataSourceRevalidateMs={2_000}
        pagination
        initialState={{
          pagination: { paginationModel: { pageSize: 5, page: 0 }, rowCount: 0 },
        }}
        pageSizeOptions={[5, 10]}
        disableColumnSorting
        disableColumnFilter
      />
    </div>
  );
}

서버 사이드 데이터 업데이트하기

Data Source는 서버의 데이터를 업데이트하기 위한 선택적 updateRow() 메서드를 지원해요.

이 메서드는 업데이트된 행으로 resolve되거나 업데이트 오류가 있으면 reject되는 promise를 반환해요. promise가 resolve되면 Grid는 행을 업데이트하고 캐시를 변경해요. 오류가 있으면 onDataSourceError()가, 이어지는 오류 처리 섹션에 설명된 params를 담은 오류 객체와 함께 트리거돼요.

 const dataSource: GridDataSource = {
  getRows: async (params: GridGetRowsParams) => {
    // fetch rows from the server
  },
+ updateRow: async (params: GridUpdateRowParams) => {
+   // update row on the server
+ },
 }
import * as React from 'react';
import { DataGridPro, GridDataSource, useGridApiRef } from '@mui/x-data-grid-pro';
import { useMockServer } from '@mui/x-data-grid-generator';
import Button from '@mui/material/Button';

export default function ServerSideEditing() {
  const apiRef = useGridApiRef();
  const {
    columns,
    initialState: initState,
    fetchRows,
    editRow,
  } = useMockServer({ editable: true }, { useCursorPagination: false });

  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),
        });
        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;
      },
    }),
    [fetchRows, editRow],
  );

  const initialState = React.useMemo(
    () => ({
      ...initState,
      pagination: {
        paginationModel: { pageSize: 10, page: 0 },
        rowCount: 0,
      },
    }),
    [initState],
  );

  return (
    <div style={{ width: '100%' }}>
      <Button
        onClick={() => {
          apiRef.current?.dataSource.cache.clear();
        }}
      >
        Clear cache
      </Button>
      <div style={{ height: 400 }}>
        <DataGridPro
          apiRef={apiRef}
          columns={columns}
          dataSource={dataSource}
          pagination
          initialState={initialState}
          pageSizeOptions={[10, 20, 50]}
        />
      </div>
    </div>
  );
}

행을 병합하는 대신 교체하기

resolve된 행은 기존 행에 병합되어 새 객체가 만들어져요. 대신 resolve된 행을 그대로 저장하려면 행 교체로 resolve하세요. 행이 프로토타입 체인, #private 필드, 또는 객체 정체성(object identity)이 업데이트 동안 살아남아야 하는 클래스 인스턴스일 때 사용하세요.

const dataSource: GridDataSource = {
  getRows: async (params: GridGetRowsParams) => {
    // fetch rows from the server
  },
  updateRow: async (params: GridUpdateRowParams) => {
    const response = await updateRowOnServer(params.updatedRow);
    return { _action: 'replace', row: MyRowClass.fromJSON(response) };
  },
};

이 경우 apiRef.current.getRow(id)는 row에 제공된 바로 그 인스턴스를 반환해요. getRows()가 resolve한 행은 항상 그대로 저장되므로, 이렇게 하면 편집이 초기 가져오기와 일관되게 유지돼요.

:::warning updateRow() 메서드를 사용할 때 Data Source 캐시는 성공적인 업데이트 후 자동으로 지워져서 오래된 데이터가 표시되는 것을 방지해요. 즉, 이전에 캐시된 데이터는 다음 요청 때 다시 가져와져요.

편집 작업과 함께 캐싱이 필요한 앱은 서버 사이드 캐싱 구현을 고려해 보세요.

편집 작업 중 클라이언트 캐시를 유지해야 하는 특정 사용 사례가 있다면 GitHub에 이슈를 열어 요구 사항을 파악할 수 있게 해 주세요. :::

:::warning 편집된 행의 현재 페이지에서의 위치와 가시성은 유지돼요—정렬이나 필터링 같은 기능이 활성화되어 있어도 말이죠—그리고 값이 업데이트된 후 행에 적용돼요. 위치나 가시성의 변화는 페이지가 다시 가져와질 때 적용돼요.

dataSource.fetchRows() API 메서드를 호출해서 수동으로 재가져오기를 트리거할 수 있어요. :::

오류 처리 (Error handling)

onDataSourceError()로 오류 핸들러 함수를 제공해서 Data Source와 관련된 오류를 처리할 수 있어요. 이 함수는 데이터 가져오기나 업데이트에 오류가 있을 때마다 호출돼요. 이 함수는 GridGetRowsError | GridUpdateRowError 타입의 오류 객체를 받아요. 각 오류 타입은 콜백에 인자로 전달되는 해당 error.params 타입을 가져요.

Error type error.params type
GridGetRowsError GridGetRowsParams
GridUpdateRowError GridUpdateRowParams
<DataGrid
  columns={columns}
  dataSource={customDataSource}
  onDataSourceError={(error) => {
    if (error instanceof GridGetRowsError) {
      // `error.params` is of type `GridGetRowsParams`
      // fetch related logic, e.g set an overlay state
    }
    if (error instanceof GridUpdateRowError) {
      // `error.params` is of type `GridUpdateRowParams`
      // update related logic, e.g set a snackbar state
    }
  }}
/>

아래 데모는 요청이 실패할 때 오류 메시지를 표시하는 커스텀 Snackbar 컴포넌트를 렌더링해요. 상단의 체크박스와 Refetch rows 버튼으로 시뮬레이션할 수 있어요. 단순함을 위해 캐싱은 비활성화됐어요.

import * as React from 'react';
import {
  DataGrid,
  useGridApiRef,
  GridInitialState,
  GridDataSource,
  GridGetRowsError,
} from '@mui/x-data-grid';
import Button from '@mui/material/Button';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import Snackbar from '@mui/material/Snackbar';
import Alert, { AlertProps } from '@mui/material/Alert';
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 = { editable: true };

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>;
}

export default function ServerSideErrorHandling() {
  const apiRef = useGridApiRef();
  const [error, setError] = React.useState<string>();
  const [snackbar, setSnackbar] = React.useState<AlertProps | null>(null);
  const [shouldRequestsFail, setShouldRequestsFail] = React.useState(false);

  const { fetchRows, editRow, ...props } = useMockServer(
    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),
        });
        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;
      },
    }),
    [fetchRows, editRow],
  );

  const initialState: GridInitialState = React.useMemo(
    () => ({
      ...props.initialState,
      pagination: {
        paginationModel: {
          pageSize: 5,
        },
        rowCount: 0,
      },
    }),
    [props.initialState],
  );

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

  return (
    <div style={{ width: '100%' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Button
          onClick={() => {
            setError('');
            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' }}>
        <DataGrid
          {...props}
          dataSource={dataSource}
          onDataSourceError={(dataSourceError) => {
            if (dataSourceError instanceof GridGetRowsError) {
              setError(dataSourceError.message);
              return;
            }
            setSnackbar({ children: dataSourceError.message, severity: 'error' });
          }}
          dataSourceCache={null}
          apiRef={apiRef}
          pagination
          pageSizeOptions={pageSizeOptions}
          initialState={initialState}
          showToolbar
        />
        {!!snackbar && (
          <Snackbar
            open
            anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            onClose={handleCloseSnackbar}
            autoHideDuration={6000}
          >
            <Alert {...snackbar} onClose={handleCloseSnackbar} />
          </Snackbar>
        )}
        {error && <ErrorOverlay error={error} />}
      </div>
    </div>
  );
}

API

더 알아보기

더 자세한 내용은 MUI X Data Grid 문서를 참고하세요.