forked from mui/mui-x
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ServerSideDataGridWithSWR.js
82 lines (74 loc) · 2.1 KB
/
ServerSideDataGridWithSWR.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import * as React from 'react';
import { DataGridPro } from '@mui/x-data-grid-pro';
import { useMockServer } from '@mui/x-data-grid-generator';
import { useSWRConfig } from 'swr';
const serverOptions = { useCursorPagination: false };
const dataSetOptions = {};
function ServerSideDataGridWithSWR() {
const { fetchRows, columns, initialState } = useMockServer(
dataSetOptions,
serverOptions,
);
const dataSource = React.useMemo(
() => ({
getRows: async (params) => {
const urlParams = new URLSearchParams({
paginationModel: encodeURIComponent(
JSON.stringify(params.paginationModel),
),
filterModel: encodeURIComponent(JSON.stringify(params.filterModel)),
sortModel: encodeURIComponent(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 { cache: swrCache } = useSWRConfig();
const cache = React.useMemo(
() => ({
getKey: (params) => JSON.stringify(params),
set: (key, value) => {
swrCache.set(key, { data: value });
},
get: (key) => {
return swrCache.get(key)?.data;
},
clear: () => {
const keys = swrCache.keys();
Array.from(keys).forEach((key) => {
swrCache.delete(key);
});
},
}),
[swrCache],
);
const initialStateWithPagination = React.useMemo(
() => ({
...initialState,
pagination: {
paginationModel: { pageSize: 10, page: 0 },
},
}),
[initialState],
);
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
columns={columns}
unstable_dataSource={dataSource}
unstable_dataSourceCache={cache}
pagination
initialState={initialStateWithPagination}
pageSizeOptions={[10, 20, 50]}
/>
</div>
);
}
export default ServerSideDataGridWithSWR;