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

Data Grid - 편집 지속성(Editing persistence)

원문 보기 위키 갱신

편집된 행을 지속시킬 수 있어요.

출처: MUI X documentation

본문

processRowUpdate() 콜백

사용자가 편집을 중지하는 동작을 수행하면 processRowUpdate() 콜백이 트리거돼요. 이를 사용해 새 값을 서버로 보내고 데이터베이스나 다른 저장 방식에 저장하세요. 콜백은 세 개의 인자를 받아요:

  1. valueSetter()가 반환한 새 값이 적용된 업데이트된 행.
  2. 편집 전 행의 원래 값.
  3. rowId 같은 추가 속성을 가진 객체.

processRowUpdate()가 Data Grid 내부 상태를 업데이트하려면 행 객체를 반환해야 한다는 점을 유의하세요. 반환된 값은 나중에 apiRef.current.updateRows() 호출의 인자로 사용돼요.

<DataGrid
  rows={rows}
  columns={columns}
  processRowUpdate={(updatedRow, originalRow) =>
    mySaveOnServerFunction(updatedRow);
  }
  onProcessRowUpdateError={handleProcessRowUpdateError}
/>

Data Grid의 내부 상태에서 행을 삭제하고 싶다면 processRowUpdate() 콜백에서 행 객체에 추가 속성 _action: 'delete'를 반환할 수 있어요. 그러면 행이 Data Grid의 내부 상태에서 제거돼요. rows prop을 업데이트하거나 setRows() API 메서드를 사용하는 것보다 행을 삭제하는 더 성능 좋은 방법이에요. processRowUpdate가 내부적으로 updateRows()를 사용하며, 이는 행 트리의 전체 재생성을 일으키지 않기 때문이에요.

<DataGrid
  {...otherProps}
  processRowUpdate={(updatedRow, originalRow) => {
    if (shouldDeleteRow(updatedRow)) {
      return { ...updatedRow, _action: 'delete' };
    }
    return updatedRow;
  }}
/>

위 예제에서 shouldDeleteRow는 업데이트된 행 데이터를 기반으로 행을 삭제할지 판단하는 함수예요. shouldDeleteRow가 true를 반환하면 행이 Data Grid의 내부 상태에서 삭제돼요.

행을 병합 대신 교체하기

processRowUpdate()에서 행 교체를 반환해서 row를 기존 행에 병합하는 대신 새 행으로 저장할 수도 있어요. 행이 프로토타입 체인, #private 필드 또는 객체 정체성이 편집 후에도 유지되어야 하는 클래스 인스턴스일 때 사용하세요. processRowUpdate()가 받는 업데이트된 행은 항상 일반 객체입니다. 편집된 값이 적용된 초안(draft)이므로, 일반적으로 변경을 지속한 후 서버 응답에서 적절한 인스턴스를 만들어야 해요:

<DataGrid
  {...otherProps}
  processRowUpdate={async (updatedRow, originalRow) => {
    const response = await mySaveOnServerFunction(updatedRow);
    return { _action: 'replace', row: MyRowClass.fromJSON(response) };
  }}
/>

이 경우 편집이 저장된 후 apiRef.current.getRow(id)는 row에 제공된 바로 그 인스턴스를 반환해요. Data Grid는 참조 변경에 의존해 다시 렌더링하므로, 그 인스턴스는 현재 저장된 객체와 다른 객체여야 해요.

서버 측 검증

processRowUpdate()에서 저장 과정을 취소해야 한다면 — 예를 들어 데이터베이스 검증이 실패하거나 사용자가 변경을 거부하고 싶을 때 — 두 가지 옵션이 있어요:

  1. promise를 reject해서 내부 상태가 업데이트되지 않고 셀이 편집 모드에 머물게 하기.
  2. promise를 두 번째 인자(편집 전 원래 행)로 resolve해서 내부 상태가 업데이트되지 않고 셀이 편집 모드를 종료하게 하기.

다음 데모는 첫 번째 옵션인 promise를 reject하는 방식을 구현해요. 입력하면서 검증하는 대신 서버에서 검증을 시뮬레이션해요. 새 이름이 비어 있으면 행 저장을 담당하는 promise가 reject되고 셀이 편집 모드에 남아요.

이 데모는 processRowUpdate()가 내부 상태에 저장될 행 모델을 전처리할 수 있음도 보여줘요.

추가로 onProcessRowUpdateError()가 호출되어 오류 메시지를 표시해요.

편집 모드를 종료하려면 Escape를 누르거나 유효한 이름을 입력하세요.

import * as React from 'react';
import {
  DataGrid,
  GridRowModel,
  GridColDef,
  GridRowId,
  GridRowsProp,
} from '@mui/x-data-grid';
import {
  randomCreatedDate,
  randomTraderName,
  randomUpdatedDate,
} from '@mui/x-data-grid-generator';
import Snackbar from '@mui/material/Snackbar';
import Alert, { AlertProps } from '@mui/material/Alert';

interface User {
  name: string;
  age: number;
  id: GridRowId;
  dateCreated: Date;
  lastLogin: Date;
}

const useFakeMutation = () => {
  return React.useCallback(
    (user: Partial<User>) =>
      new Promise<Partial<User>>((resolve, reject) => {
        setTimeout(() => {
          if (user.name?.trim() === '') {
            reject(new Error('Error while saving user: name cannot be empty.'));
          } else {
            resolve({ ...user, name: user.name?.toUpperCase() });
          }
        }, 200);
      }),
    [],
  );
};

export default function ServerSidePersistence() {
  const mutateRow = useFakeMutation();

  const [snackbar, setSnackbar] = React.useState<Pick<
    AlertProps,
    'children' | 'severity'
  > | null>(null);

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

  const processRowUpdate = React.useCallback(
    async (newRow: GridRowModel) => {
      // Make the HTTP request to save in the backend
      const response = await mutateRow(newRow);
      setSnackbar({ children: 'User successfully saved', severity: 'success' });
      return response;
    },
    [mutateRow],
  );

  const handleProcessRowUpdateError = React.useCallback((error: Error) => {
    setSnackbar({ children: error.message, severity: 'error' });
  }, []);

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={columns}
        processRowUpdate={processRowUpdate}
        onProcessRowUpdateError={handleProcessRowUpdateError}
      />
      {!!snackbar && (
        <Snackbar
          open
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
          onClose={handleCloseSnackbar}
          autoHideDuration={6000}
        >
          <Alert {...snackbar} onClose={handleCloseSnackbar} />
        </Snackbar>
      )}
    </div>
  );
}

const columns: GridColDef[] = [
  { field: 'name', headerName: 'Name', width: 180, editable: true, rowHeader: true },
  {
    field: 'age',
    headerName: 'Age',
    type: 'number',
    editable: true,
    align: 'left',
    headerAlign: 'left',
  },
  {
    field: 'dateCreated',
    headerName: 'Date Created',
    type: 'date',
    width: 180,
    editable: true,
  },
  {
    field: 'lastLogin',
    headerName: 'Last Login',
    type: 'dateTime',
    width: 220,
    editable: true,
  },
];

const rows: GridRowsProp = [
  {
    id: 1,
    name: randomTraderName(),
    age: 25,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
  {
    id: 2,
    name: randomTraderName(),
    age: 36,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
  {
    id: 3,
    name: randomTraderName(),
    age: 19,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
  {
    id: 4,
    name: randomTraderName(),
    age: 28,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
  {
    id: 5,
    name: randomTraderName(),
    age: 23,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
];

저장 전 확인하기

두 번째 옵션 — promise를 두 번째 인자로 resolve하는 방식 — 은 사용자가 변경을 거부하고 편집 모드를 종료함으로써 저장 과정을 취소할 수 있게 해줘요. 이 경우 processRowUpdate()는 행의 원래 값으로 resolve돼요.

다음 데모는 이 접근 방식을 사용해 데이터를 서버로 보내기 전에 확인을 요청하는 방법을 보여줘요. 사용자가 변경을 수락하면 내부 상태가 그 값으로 업데이트돼요. 하지만 변경이 거부되면 내부 상태는 그대로 남고 셀은 원래 값으로 되돌아가요. 이 데모는 또한 빈 이름을 입력하지 못하게 하는 검증도 사용해요.

import * as React from 'react';
import {
  DataGrid,
  GridRowModel,
  GridColDef,
  GridRowId,
  GridRowsProp,
} from '@mui/x-data-grid';
import {
  randomCreatedDate,
  randomTraderName,
  randomUpdatedDate,
} from '@mui/x-data-grid-generator';
import Snackbar from '@mui/material/Snackbar';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import Alert, { AlertProps } from '@mui/material/Alert';

interface User {
  name: string;
  age: number;
  id: GridRowId;
  dateCreated: Date;
  lastLogin: Date;
}

const useFakeMutation = () => {
  return React.useCallback(
    (user: Partial<User>) =>
      new Promise<Partial<User>>((resolve, reject) => {
        setTimeout(() => {
          if (user.name?.trim() === '') {
            reject();
          } else {
            resolve(user);
          }
        }, 200);
      }),
    [],
  );
};

function computeMutation(newRow: GridRowModel, oldRow: GridRowModel) {
  if (newRow.name !== oldRow.name) {
    return `Name from '${oldRow.name}' to '${newRow.name}'`;
  }
  if (newRow.age !== oldRow.age) {
    return `Age from '${oldRow.age || ''}' to '${newRow.age || ''}'`;
  }
  return null;
}

export default function AskConfirmationBeforeSave() {
  const mutateRow = useFakeMutation();
  const noButtonRef = React.useRef<HTMLButtonElement>(null);
  const [promiseArguments, setPromiseArguments] = React.useState<any>(null);

  const [snackbar, setSnackbar] = React.useState<Pick<
    AlertProps,
    'children' | 'severity'
  > | null>(null);

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

  const processRowUpdate = React.useCallback(
    (newRow: GridRowModel, oldRow: GridRowModel) =>
      new Promise<GridRowModel>((resolve, reject) => {
        const mutation = computeMutation(newRow, oldRow);
        if (mutation) {
          // Save the arguments to resolve or reject the promise later
          setPromiseArguments({ resolve, reject, newRow, oldRow });
        } else {
          resolve(oldRow); // Nothing was changed
        }
      }),
    [],
  );

  const handleNo = () => {
    const { oldRow, resolve } = promiseArguments;
    resolve(oldRow); // Resolve with the old row to not update the internal state
    setPromiseArguments(null);
  };

  const handleYes = async () => {
    const { newRow, oldRow, reject, resolve } = promiseArguments;

    try {
      // Make the HTTP request to save in the backend
      const response = await mutateRow(newRow);
      setSnackbar({ children: 'User successfully saved', severity: 'success' });
      resolve(response);
      setPromiseArguments(null);
    } catch (error) {
      setSnackbar({ children: 'Name cannot be empty', severity: 'error' });
      reject(oldRow);
      setPromiseArguments(null);
    }
  };

  const handleEntered = () => {
    // The `autoFocus` is not used because, if used, the same Enter that saves
    // the cell triggers "No". Instead, we manually focus the "No" button once
    // the dialog is fully open.
    // noButtonRef.current?.focus();
  };

  const renderConfirmDialog = () => {
    if (!promiseArguments) {
      return null;
    }

    const { newRow, oldRow } = promiseArguments;
    const mutation = computeMutation(newRow, oldRow);

    return (
      <Dialog
        maxWidth="xs"
        open={!!promiseArguments}
        slotProps={{
          transition: { onEntered: handleEntered },
        }}
      >
        <DialogTitle>Are you sure?</DialogTitle>
        <DialogContent dividers>
          {`Pressing 'Yes' will change ${mutation}.`}
        </DialogContent>
        <DialogActions>
          <Button ref={noButtonRef} onClick={handleNo}>
            No
          </Button>
          <Button onClick={handleYes}>Yes</Button>
        </DialogActions>
      </Dialog>
    );
  };

  return (
    <div style={{ height: 400, width: '100%' }}>
      {renderConfirmDialog()}
      <DataGrid rows={rows} columns={columns} processRowUpdate={processRowUpdate} />
      {!!snackbar && (
        <Snackbar open onClose={handleCloseSnackbar} autoHideDuration={6000}>
          <Alert {...snackbar} onClose={handleCloseSnackbar} />
        </Snackbar>
      )}
    </div>
  );
}

const columns: GridColDef[] = [
  { field: 'name', headerName: 'Name', width: 180, editable: true, rowHeader: true },
  { field: 'age', headerName: 'Age', type: 'number', editable: true },
  {
    field: 'dateCreated',
    headerName: 'Date Created',
    type: 'date',
    width: 180,
  },
  {
    field: 'lastLogin',
    headerName: 'Last Login',
    type: 'dateTime',
    width: 220,
  },
];

const rows: GridRowsProp = [
  {
    id: 1,
    name: randomTraderName(),
    age: 25,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
  {
    id: 2,
    name: randomTraderName(),
    age: 36,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
  {
    id: 3,
    name: randomTraderName(),
    age: 19,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
  {
    id: 4,
    name: randomTraderName(),
    age: 28,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
  {
    id: 5,
    name: randomTraderName(),
    age: 23,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
  },
];

API

더 알아보기 (Learn more)