Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DataGrid] Data source with editing #16045

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions docs/data/data-grid/server-side-data/ServerSideEditing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import * as React from 'react';
import { DataGridPro, 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 = 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 (rowId, updatedRow) => {
const syncedRow = await editRow(rowId, 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.unstable_dataSource.cache.clear();
}}
>
Clear cache
</Button>
<div style={{ height: 400 }}>
<DataGridPro
apiRef={apiRef}
columns={columns}
unstable_dataSource={dataSource}
pagination
initialState={initialState}
pageSizeOptions={[10, 20, 50]}
/>
</div>
</div>
);
}
71 changes: 71 additions & 0 deletions docs/data/data-grid/server-side-data/ServerSideEditing.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
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 (rowId, updatedRow) => {
const syncedRow = await editRow(rowId, 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.unstable_dataSource.cache.clear();
}}
>
Clear cache
</Button>
<div style={{ height: 400 }}>
<DataGridPro
apiRef={apiRef}
columns={columns}
unstable_dataSource={dataSource}
pagination
initialState={initialState}
pageSizeOptions={[10, 20, 50]}
/>
</div>
</div>
);
}
8 changes: 4 additions & 4 deletions docs/data/data-grid/server-side-data/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,12 +290,12 @@ The first argument of this function is the error object, and the second argument

{{"demo": "ServerSideErrorHandling.js", "bg": "inline"}}

## Updating data 🚧
## Updating data

This feature is yet to be implemented, when completed, the method `unstable_dataSource.updateRow` will be called with the `GridRowModel` whenever the user edits a row.
It will work in a similar way as the `processRowUpdate` prop.
The data source also supports updating data on the server.
Use data source's `updateRow` method to update a row on the server as the demo below shows.

Feel free to upvote the related GitHub [issue](https://github.com/mui/mui-x/issues/13261) to see this feature land faster.
{{"demo": "ServerSideEditing.js", "bg": "inline"}}

## API

Expand Down
35 changes: 35 additions & 0 deletions packages/x-data-grid-generator/src/hooks/useMockServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
GridColDef,
GridInitialState,
GridColumnVisibilityModel,
GridRowId,
} from '@mui/x-data-grid-premium';
import { extrapolateSeed, deepFreeze } from './useDemoData';
import { getCommodityColumns } from '../columns/commodities.columns';
Expand Down Expand Up @@ -40,6 +41,7 @@ type UseMockServerResponse = {
getGroupKey?: (row: GridRowModel) => string;
getChildrenCount?: (row: GridRowModel) => number;
fetchRows: (url: string) => Promise<GridGetRowsResponse>;
editRow: (rowId: GridRowId, updatedRow: GridRowModel) => Promise<GridRowModel>;
loadNewData: () => void;
};

Expand Down Expand Up @@ -357,12 +359,45 @@ export const useMockServer = (
],
);

const editRow = React.useCallback(
async (rowId: GridRowId, updatedRow: GridRowModel) => {
return new Promise<GridRowModel>((resolve, reject) => {
const minDelay = serverOptions?.minDelay ?? DEFAULT_SERVER_OPTIONS.minDelay;
const maxDelay = serverOptions?.maxDelay ?? DEFAULT_SERVER_OPTIONS.maxDelay;
const delay = randomInt(minDelay, maxDelay);

if (shouldRequestsFailRef.current) {
setTimeout(() => reject(new Error('Could not update the row')), delay);
return;
}

setData((prevData) => {
const newData = { ...prevData } as GridDemoData;
newData.rows = newData.rows?.map((row) => (row.id === rowId ? updatedRow : row));
const cacheKey = `${options.dataSet}-${options.rowLength}-${index}-${options.maxColumns}`;
dataCache.set(cacheKey, newData!);
setTimeout(() => resolve(updatedRow), delay);
return newData;
});
});
},
[
index,
options.dataSet,
options.maxColumns,
options.rowLength,
serverOptions?.maxDelay,
serverOptions?.minDelay,
],
);

return {
columns: columnsWithDefaultColDef,
initialState: options.dataSet === 'Movies' ? {} : initialState,
getGroupKey,
getChildrenCount,
fetchRows,
editRow,
loadNewData: () => {
setIndex((oldIndex) => oldIndex + 1);
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GridRowId } from '@mui/x-data-grid';
import { GridRowId, GridRowModel } from '@mui/x-data-grid';
import { GridDataSourceCache, GridGetRowsParams } from '@mui/x-data-grid/internals';

export interface GridDataSourceState {
Expand Down Expand Up @@ -52,4 +52,10 @@ export interface GridDataSourcePrivateApi {
* Resets the data source state.
*/
resetDataSourceState: () => void;
/**
* Mutates a row in the cache.
* @param {GridRowId} id The id of the row to be mutated.
* @param {GridRowModel} row The row to be mutated.
*/
mutateRowInCache: (id: GridRowId, row: GridRowModel) => void;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import {
gridPaginationModelSelector,
GRID_ROOT_GROUP_ID,
GridEventListener,
GridRowId,
} from '@mui/x-data-grid';
import {
GridGetRowsResponse,
gridRowGroupsToFetchSelector,
GridStateInitializer,
GridStrategyGroup,
GridStrategyProcessor,
GridGetRowsParams,
GridDataSourceCache,
runIf,
} from '@mui/x-data-grid/internals';
Expand Down Expand Up @@ -74,6 +76,7 @@ export const useGridDataSourceBase = <Api extends GridPrivateApiPro>(
cacheOptions?: GridDataSourceCacheDefaultConfig;
} = {},
) => {
const rowIdToGetRowsParams = React.useRef<Record<GridRowId, GridGetRowsParams>>({});
const setStrategyAvailability = React.useCallback(() => {
apiRef.current.setStrategyAvailability(
GridStrategyGroup.DataSource,
Expand Down Expand Up @@ -156,6 +159,9 @@ export const useGridDataSourceBase = <Api extends GridPrivateApiPro>(
const cacheResponses = cacheChunkManager.splitResponse(fetchParams, getRowsResponse);
cacheResponses.forEach((response, key) => {
cache.set(key, response);
response.rows.forEach((row) => {
rowIdToGetRowsParams.current[row.id] = fetchParams;
});
});

if (lastRequestId.current === requestId) {
Expand Down Expand Up @@ -323,6 +329,28 @@ export const useGridDataSourceBase = <Api extends GridPrivateApiPro>(
[apiRef],
);

const mutateRowInCache = React.useCallback<GridDataSourcePrivateApi['mutateRowInCache']>(
(rowId, rowUpdate) => {
const getRowsParams = rowIdToGetRowsParams.current[rowId];
if (!getRowsParams) {
return;
}
const cachedData = cache.get(getRowsParams);
if (!cachedData) {
return;
}
const updatedRows = [...cachedData.rows];
// TODO: Accomodate `props.getRowId`
const rowIndex = updatedRows.findIndex((row) => row.id === rowId);
if (rowIndex === -1) {
return;
}
updatedRows[rowIndex] = rowUpdate;
cache.set(getRowsParams, { ...cachedData, rows: updatedRows });
},
[cache],
);

const handleStrategyActivityChange = React.useCallback<
GridEventListener<'strategyAvailabilityChange'>
>(() => {
Expand Down Expand Up @@ -374,6 +402,7 @@ export const useGridDataSourceBase = <Api extends GridPrivateApiPro>(
const dataSourcePrivateApi: GridDataSourcePrivateApi = {
fetchRowChildren,
resetDataSourceState,
mutateRowInCache,
};

const isFirstRender = React.useRef(true);
Expand Down
2 changes: 0 additions & 2 deletions packages/x-data-grid-pro/src/models/dataGridProProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import type {
DataGridProSharedPropsWithDefaultValue,
DataGridProSharedPropsWithoutDefaultValue,
GridDataSourceCache,
GridGetRowsParams,
} from '@mui/x-data-grid/internals';
import type { GridPinnedRowsProp } from '../hooks/features/rowPinning';
import { GridApiPro } from './gridApiPro';
Expand Down Expand Up @@ -160,7 +159,6 @@ export interface DataGridProPropsWithDefaultValue<R extends GridValidRowModel =

interface DataGridProDataSourceProps {
unstable_dataSourceCache?: GridDataSourceCache | null;
unstable_onDataSourceError?: (error: Error, params: GridGetRowsParams) => void;
}

interface DataGridProRegularProps<R extends GridValidRowModel> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
GridCellEditStopReasons,
} from '../../../models/params/gridEditCellParams';
import { getDefaultCellValue } from './utils';
import { GridUpdateRowParams } from '../../../models/gridDataSource';

export const useGridCellEditing = (
apiRef: React.RefObject<GridPrivateApiCommunity>,
Expand All @@ -53,6 +54,8 @@ export const useGridCellEditing = (
| 'onCellModesModelChange'
| 'onProcessRowUpdateError'
| 'signature'
| 'unstable_dataSource'
| 'unstable_onDataSourceError'
>,
) => {
const [cellModesModel, setCellModesModel] = React.useState<GridCellModesModel>({});
Expand Down Expand Up @@ -425,7 +428,43 @@ export const useGridCellEditing = (

const rowUpdate = apiRef.current.getRowWithUpdatedValuesFromCellEditing(id, field);

if (processRowUpdate) {
if (props.unstable_dataSource?.updateRow) {
const handleError = (errorThrown: any, updateParams: GridUpdateRowParams) => {
prevCellModesModel.current[id][field].mode = GridCellModes.Edit;
// Revert the mode in the cellModesModel prop back to "edit"
updateFieldInCellModesModel(id, field, { mode: GridCellModes.Edit });

if (typeof props.unstable_onDataSourceError === 'function') {
props.unstable_onDataSourceError(errorThrown, updateParams);
} else if (process.env.NODE_ENV !== 'production') {
warnOnce(
[
'MUI X: A call to `unstable_dataSource.updateRow()` threw an error which was not handled because `unstable_onDataSourceError` is missing.',
'To handle the error pass a callback to the `unstable_onDataSourceError` prop, for example `<DataGrid unstable_onDataSourceError={(error, params) => ...} />`.',
'For more detail, see https://mui.com/x/react-data-grid/server-side-data/#error-handling.',
],
'error',
);
}
};

const row = apiRef.current.getRow(id)!;

try {
Promise.resolve(props.unstable_dataSource.updateRow(id, rowUpdate, row))
.then((finalRowUpdate) => {
apiRef.current.updateRows([finalRowUpdate]);
// @ts-expect-error TODO: Move basic dataSource to community
apiRef.current.mutateRowInCache?.(id, rowUpdate);
finishCellEditMode();
})
.catch((errorThrown) =>
handleError(errorThrown, { rowId: id, previousRow: row, updatedRow: rowUpdate }),
);
} catch (errorThrown) {
handleError(errorThrown, { rowId: id, previousRow: row, updatedRow: rowUpdate });
}
} else if (processRowUpdate) {
const handleError = (errorThrown: any) => {
prevCellModesModel.current[id][field].mode = GridCellModes.Edit;
// Revert the mode in the cellModesModel prop back to "edit"
Expand Down
Loading
Loading