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

[docs] Use updateRows method for list view demos #15732

Merged
merged 1 commit into from
Dec 10, 2024
Merged
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
8 changes: 4 additions & 4 deletions docs/data/data-grid/list-view/ListView.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import IconButton from '@mui/material/IconButton';
import MessageIcon from '@mui/icons-material/Message';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import GridIcon from '@mui/icons-material/GridOn';
import ListIcon from '@mui/icons-material/TableRowsOutlined';
import GridViewIcon from '@mui/icons-material/ViewModule';
import ListViewIcon from '@mui/icons-material/ViewList';
Comment on lines +11 to +12
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drive by icon update, these are more consistent with the other icons we use (filled, not outlined).


function MessageAction(params) {
const handleMessage = (event) => {
Expand Down Expand Up @@ -77,7 +77,7 @@ function Toolbar({ view, onChangeView }) {
value="grid"
selected={view === 'grid'}
>
<GridIcon fontSize="small" /> Grid
<GridViewIcon fontSize="small" /> Grid
</ToggleButton>
<ToggleButton
size="small"
Expand All @@ -86,7 +86,7 @@ function Toolbar({ view, onChangeView }) {
value="list"
selected={view === 'list'}
>
<ListIcon fontSize="small" /> List
<ListViewIcon fontSize="small" /> List
</ToggleButton>
</ToggleButtonGroup>
</GridToolbarContainer>
Expand Down
8 changes: 4 additions & 4 deletions docs/data/data-grid/list-view/ListView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import IconButton from '@mui/material/IconButton';
import MessageIcon from '@mui/icons-material/Message';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import GridIcon from '@mui/icons-material/GridOn';
import ListIcon from '@mui/icons-material/TableRowsOutlined';
import GridViewIcon from '@mui/icons-material/ViewModule';
import ListViewIcon from '@mui/icons-material/ViewList';

declare module '@mui/x-data-grid' {
interface ToolbarPropsOverrides {
Expand Down Expand Up @@ -96,7 +96,7 @@ function Toolbar({ view, onChangeView }: ToolbarProps) {
value="grid"
selected={view === 'grid'}
>
<GridIcon fontSize="small" /> Grid
<GridViewIcon fontSize="small" /> Grid
</ToggleButton>
<ToggleButton
size="small"
Expand All @@ -105,7 +105,7 @@ function Toolbar({ view, onChangeView }: ToolbarProps) {
value="list"
selected={view === 'list'}
>
<ListIcon fontSize="small" /> List
<ListViewIcon fontSize="small" /> List
</ToggleButton>
</ToggleButtonGroup>
</GridToolbarContainer>
Expand Down
106 changes: 53 additions & 53 deletions docs/data/data-grid/list-view/ListViewAdvanced.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ export default function ListViewAdvanced(props) {

const apiRef = useGridApiRef();

const [rows, setRows] = React.useState(INITIAL_ROWS);

const [loading, setLoading] = React.useState(false);

const [overlayState, setOverlayState] = React.useState({
Expand All @@ -51,65 +49,67 @@ export default function ListViewAdvanced(props) {
setOverlayState({ overlay: null, params: null });
};

const handleDelete = React.useCallback((ids) => {
setRows((prevRows) => prevRows.filter((row) => !ids.includes(row.id)));
}, []);
const handleDelete = React.useCallback(
(ids) => {
apiRef.current.updateRows(ids.map((id) => ({ id, _action: 'delete' })));
},
[apiRef],
);

const handleUpdate = React.useCallback((id, field, value) => {
setRows((prevRows) =>
prevRows.map((row) =>
row.id === id
? { ...row, [field]: value, updatedAt: new Date().toISOString() }
: row,
),
);
}, []);
const handleUpdate = React.useCallback(
(id, field, value) => {
const updatedAt = new Date().toISOString();
apiRef.current.updateRows([{ id, [field]: value, updatedAt }]);
},
[apiRef],
);

const handleUpload = React.useCallback((event) => {
if (!event.target.files) {
return;
}
const handleUpload = React.useCallback(
(event) => {
if (!event.target.files) {
return;
}

const file = event.target.files[0];
const createdAt = new Date().toISOString();
const file = event.target.files[0];
const createdAt = new Date().toISOString();

const fileType = file.type.split('/')[1];
const fileType = file.type.split('/')[1];

// validate file type
if (!FILE_TYPES.includes(fileType)) {
alert('Invalid file type');
return;
}
// validate file type
if (!FILE_TYPES.includes(fileType)) {
alert('Invalid file type');
return;
}

const row = {
id: randomId(),
name: file.name,
description: '',
type: fileType,
size: file.size,
createdBy: 'Kenan Yusuf',
createdAt,
updatedAt: createdAt,
state: 'pending',
};
const row = {
id: randomId(),
name: file.name,
description: '',
type: fileType,
size: file.size,
createdBy: 'Kenan Yusuf',
createdAt,
updatedAt: createdAt,
state: 'pending',
};

event.target.value = '';
event.target.value = '';

// Add temporary row
setLoading(true);
setRows((prevRows) => [...prevRows, row]);
// Add temporary row
setLoading(true);
apiRef.current.updateRows([row]);

// Simulate server response time
const timeout = Math.floor(Math.random() * 3000) + 2000;
setTimeout(() => {
const uploadedRow = { ...row, state: 'uploaded' };
setRows((prevRows) =>
prevRows.map((r) => (r.id === row.id ? uploadedRow : r)),
);
setOverlayState({ overlay: 'actions', params: { row } });
setLoading(false);
}, timeout);
}, []);
// Simulate server response time
const timeout = Math.floor(Math.random() * 3000) + 2000;
setTimeout(() => {
const uploadedRow = { ...row, state: 'uploaded' };
apiRef.current.updateRows([uploadedRow]);
setOverlayState({ overlay: 'actions', params: { row } });
setLoading(false);
}, timeout);
},
[apiRef],
);

const columns = React.useMemo(
() => [
Expand Down Expand Up @@ -272,7 +272,7 @@ export default function ListViewAdvanced(props) {
>
<DataGridPremium
apiRef={apiRef}
rows={rows}
rows={INITIAL_ROWS}
columns={columns}
loading={loading}
slots={{ toolbar: Toolbar }}
Expand Down
33 changes: 13 additions & 20 deletions docs/data/data-grid/list-view/ListViewAdvanced.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
DataGridPremium,
GridRowId,
gridClasses,
GridRowModel,
} from '@mui/x-data-grid-premium';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
Expand Down Expand Up @@ -56,8 +55,6 @@ export default function ListViewAdvanced(props: Props) {

const apiRef = useGridApiRef();

const [rows, setRows] = React.useState<GridRowModel<RowModel>[]>(INITIAL_ROWS);

const [loading, setLoading] = React.useState(false);

const [overlayState, setOverlayState] = React.useState<{
Expand All @@ -72,25 +69,23 @@ export default function ListViewAdvanced(props: Props) {
setOverlayState({ overlay: null, params: null });
};

const handleDelete = React.useCallback((ids: GridRowId[]) => {
setRows((prevRows) => prevRows.filter((row) => !ids.includes(row.id)));
}, []);
const handleDelete = React.useCallback(
(ids: GridRowId[]) => {
apiRef.current.updateRows(ids.map((id) => ({ id, _action: 'delete' })));
},
[apiRef],
);

const handleUpdate = React.useCallback(
(
id: GridRowId,
field: GridRowParams<RowModel>['columns'][number]['field'],
value: string,
) => {
setRows((prevRows) =>
prevRows.map((row) =>
row.id === id
? { ...row, [field]: value, updatedAt: new Date().toISOString() }
: row,
),
);
const updatedAt = new Date().toISOString();
apiRef.current.updateRows([{ id, [field]: value, updatedAt }]);
},
[],
[apiRef],
);

const handleUpload = React.useCallback(
Expand Down Expand Up @@ -126,20 +121,18 @@ export default function ListViewAdvanced(props: Props) {

// Add temporary row
setLoading(true);
setRows((prevRows) => [...prevRows, row]);
apiRef.current.updateRows([row]);

// Simulate server response time
const timeout = Math.floor(Math.random() * 3000) + 2000;
setTimeout(() => {
const uploadedRow: RowModel = { ...row, state: 'uploaded' };
setRows((prevRows) =>
prevRows.map((r) => (r.id === row.id ? uploadedRow : r)),
);
apiRef.current.updateRows([uploadedRow]);
setOverlayState({ overlay: 'actions', params: { row } });
setLoading(false);
}, timeout);
},
[],
[apiRef],
);

const columns: GridColDef[] = React.useMemo(
Expand Down Expand Up @@ -303,7 +296,7 @@ export default function ListViewAdvanced(props: Props) {
>
<DataGridPremium
apiRef={apiRef}
rows={rows}
rows={INITIAL_ROWS}
columns={columns}
loading={loading}
slots={{ toolbar: Toolbar }}
Expand Down
50 changes: 29 additions & 21 deletions docs/data/data-grid/list-view/ListViewEdit.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import * as React from 'react';
import { DataGridPro } from '@mui/x-data-grid-pro';
import { DataGridPro, useGridApiContext } from '@mui/x-data-grid-pro';
import Stack from '@mui/material/Stack';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
Expand All @@ -28,7 +29,7 @@ const randomRole = () => {
return randomArrayItem(roles);
};

const initialRows = [
const rows = [
{
id: randomId(),
name: randomTraderName(),
Expand Down Expand Up @@ -73,10 +74,11 @@ const columns = [
];

function EditAction(props) {
const { row, onSave } = props;
const { row } = props;
const [editing, setEditing] = React.useState(false);
const [name, setName] = React.useState(row.name);
const [position, setPosition] = React.useState(row.position);
const apiRef = useGridApiContext();

const handleEdit = (event) => {
event.stopPropagation();
Expand All @@ -89,7 +91,7 @@ function EditAction(props) {

const handleSave = (event) => {
event.preventDefault();
onSave(row.id, { name, position });
apiRef.current.updateRows([{ id: row.id, name, position }]);
handleClose();
};

Expand Down Expand Up @@ -155,6 +157,20 @@ function EditAction(props) {
);
}

function DeleteAction(props) {
const { row } = props;
const apiRef = useGridApiContext();

return (
<IconButton
aria-label="Delete"
onClick={() => apiRef.current.updateRows([{ id: row.id, _action: 'delete' }])}
>
<DeleteIcon />
</IconButton>
);
}

function ListViewCell(props) {
const { row } = props;

Expand All @@ -176,28 +192,20 @@ function ListViewCell(props) {
{row.position}
</Typography>
</Stack>
<EditAction {...props} />
<Stack direction="row" sx={{ gap: 0.5 }}>
<EditAction {...props} />
<DeleteAction {...props} />
</Stack>
</Stack>
);
}

export default function ListViewEdit() {
const [rows, setRows] = React.useState(initialRows);

const updateRow = React.useCallback((id, rowUpdates) => {
setRows((prevRows) =>
prevRows.map((row) => (row.id === id ? { ...row, ...rowUpdates } : row)),
);
}, []);

const listColDef = React.useMemo(
() => ({
field: 'listColumn',
renderCell: (params) => <ListViewCell {...params} onSave={updateRow} />,
}),
[updateRow],
);
const listColDef = {
field: 'listColumn',
renderCell: (params) => <ListViewCell {...params} />,
};

export default function ListViewEdit() {
return (
<div
style={{
Expand Down
Loading
Loading