@mini_7/material-react-table-mcp 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -0
- package/data/MIGRATION.md +136 -0
- package/data/api.json +5379 -0
- package/data/examples/advanced.tsx +309 -0
- package/data/examples/aggregation-and-grouping.tsx +153 -0
- package/data/examples/aggregation-multi.tsx +105 -0
- package/data/examples/alternate-column-filtering.tsx +49 -0
- package/data/examples/alternate-detail-panel.tsx +81 -0
- package/data/examples/alternate-pagination.tsx +23 -0
- package/data/examples/basic.tsx +109 -0
- package/data/examples/chart-detail-panel.tsx +89 -0
- package/data/examples/column-actions-space.tsx +44 -0
- package/data/examples/column-alignment.tsx +70 -0
- package/data/examples/custom-column-actions.tsx +109 -0
- package/data/examples/custom-column-filtering-ui.tsx +89 -0
- package/data/examples/custom-headless.tsx +125 -0
- package/data/examples/custom-top-toolbar.tsx +88 -0
- package/data/examples/customize-display-columns.tsx +85 -0
- package/data/examples/customize-filter-components.tsx +101 -0
- package/data/examples/customize-filter-modes.tsx +73 -0
- package/data/examples/customize-filter-variants.tsx +116 -0
- package/data/examples/customize-global-filter-component.tsx +52 -0
- package/data/examples/customize-remove-column-grouping.tsx +94 -0
- package/data/examples/customize-row-selection.tsx +54 -0
- package/data/examples/customize-table-styles.tsx +100 -0
- package/data/examples/disable-column-actions.tsx +37 -0
- package/data/examples/disable-column-hiding.tsx +90 -0
- package/data/examples/disable-density-toggle.tsx +49 -0
- package/data/examples/dynamic-columns.tsx +189 -0
- package/data/examples/editing-crud-cell.tsx +377 -0
- package/data/examples/editing-crud-modal.tsx +370 -0
- package/data/examples/editing-crud-row.tsx +333 -0
- package/data/examples/editing-crud-table.tsx +369 -0
- package/data/examples/editing-crud-tree.tsx +416 -0
- package/data/examples/enable-cell-actions.tsx +76 -0
- package/data/examples/enable-click-to-copy.tsx +39 -0
- package/data/examples/enable-column-grouping.tsx +120 -0
- package/data/examples/enable-column-ordering.tsx +48 -0
- package/data/examples/enable-column-pinning.tsx +69 -0
- package/data/examples/enable-column-resizing.tsx +56 -0
- package/data/examples/enable-column-virtualization.tsx +27 -0
- package/data/examples/enable-detail-panel-conditionally.tsx +78 -0
- package/data/examples/enable-detail-panel-virtualized.tsx +80 -0
- package/data/examples/enable-expanding-tree.tsx +110 -0
- package/data/examples/enable-filter-facet-values.tsx +65 -0
- package/data/examples/enable-row-dragging.tsx +137 -0
- package/data/examples/enable-row-numbers-original.tsx +48 -0
- package/data/examples/enable-row-numbers-static.tsx +48 -0
- package/data/examples/enable-row-ordering.tsx +57 -0
- package/data/examples/enable-row-pinning-select.tsx +76 -0
- package/data/examples/enable-row-pinning-static.tsx +50 -0
- package/data/examples/enable-row-pinning-sticky.tsx +69 -0
- package/data/examples/enable-row-selection.tsx +96 -0
- package/data/examples/enable-row-virtualization.tsx +101 -0
- package/data/examples/enable-sticky-header.tsx +59 -0
- package/data/examples/expanding-tree-expanded.tsx +121 -0
- package/data/examples/expanding-tree-flat-parse.tsx +125 -0
- package/data/examples/expanding-tree-root-expanded.tsx +151 -0
- package/data/examples/export-to-csv.tsx +114 -0
- package/data/examples/export-to-pdf.tsx +104 -0
- package/data/examples/external-toolbar.tsx +108 -0
- package/data/examples/font-awesome-icons.tsx +106 -0
- package/data/examples/infinite-scrolling.tsx +208 -0
- package/data/examples/lazy-detail-panel.tsx +262 -0
- package/data/examples/lazy-sub-rows.tsx +190 -0
- package/data/examples/linear-progress.tsx +66 -0
- package/data/examples/loading.tsx +50 -0
- package/data/examples/localization-i18n-ar.tsx +65 -0
- package/data/examples/localization-i18n-az.tsx +60 -0
- package/data/examples/localization-i18n-bg.tsx +60 -0
- package/data/examples/localization-i18n-cs.tsx +60 -0
- package/data/examples/localization-i18n-da.tsx +60 -0
- package/data/examples/localization-i18n-de.tsx +60 -0
- package/data/examples/localization-i18n-el.tsx +60 -0
- package/data/examples/localization-i18n-en.tsx +60 -0
- package/data/examples/localization-i18n-es.tsx +60 -0
- package/data/examples/localization-i18n-et.tsx +60 -0
- package/data/examples/localization-i18n-fa.tsx +66 -0
- package/data/examples/localization-i18n-fi.tsx +60 -0
- package/data/examples/localization-i18n-fr.tsx +60 -0
- package/data/examples/localization-i18n-he.tsx +66 -0
- package/data/examples/localization-i18n-hr.tsx +60 -0
- package/data/examples/localization-i18n-hu.tsx +60 -0
- package/data/examples/localization-i18n-hy.tsx +65 -0
- package/data/examples/localization-i18n-id.tsx +60 -0
- package/data/examples/localization-i18n-it.tsx +60 -0
- package/data/examples/localization-i18n-ja.tsx +60 -0
- package/data/examples/localization-i18n-ko.tsx +60 -0
- package/data/examples/localization-i18n-nl.tsx +60 -0
- package/data/examples/localization-i18n-no.tsx +60 -0
- package/data/examples/localization-i18n-np.tsx +60 -0
- package/data/examples/localization-i18n-pl.tsx +60 -0
- package/data/examples/localization-i18n-pt-BR.tsx +60 -0
- package/data/examples/localization-i18n-pt.tsx +60 -0
- package/data/examples/localization-i18n-ro.tsx +60 -0
- package/data/examples/localization-i18n-ru.tsx +60 -0
- package/data/examples/localization-i18n-sk.tsx +60 -0
- package/data/examples/localization-i18n-sr-Cyrl-RS.tsx +60 -0
- package/data/examples/localization-i18n-sr-Latn-RS.tsx +60 -0
- package/data/examples/localization-i18n-sv.tsx +60 -0
- package/data/examples/localization-i18n-tr.tsx +60 -0
- package/data/examples/localization-i18n-uk.tsx +60 -0
- package/data/examples/localization-i18n-vi.tsx +60 -0
- package/data/examples/localization-i18n-zh-hans.tsx +60 -0
- package/data/examples/localization-i18n-zh-hant.tsx +60 -0
- package/data/examples/manual-selection.tsx +105 -0
- package/data/examples/minimal.tsx +78 -0
- package/data/examples/mui-theme.tsx +136 -0
- package/data/examples/multi-sorting.tsx +58 -0
- package/data/examples/persistent-state.tsx +184 -0
- package/data/examples/react-query.tsx +182 -0
- package/data/examples/remote.tsx +150 -0
- package/data/examples/row-actions-buttons.tsx +89 -0
- package/data/examples/row-actions-menu-items.tsx +64 -0
- package/data/examples/single-row-selection.tsx +98 -0
- package/data/examples/virtualized.tsx +138 -0
- package/data/guides/accessibility.md +119 -0
- package/data/guides/aggregation.md +210 -0
- package/data/guides/async-loading.md +132 -0
- package/data/guides/best-practices.md +363 -0
- package/data/guides/cell-actions.md +139 -0
- package/data/guides/click-to-copy.md +67 -0
- package/data/guides/column-actions.md +69 -0
- package/data/guides/column-filtering.md +366 -0
- package/data/guides/column-grouping.md +192 -0
- package/data/guides/column-hiding.md +133 -0
- package/data/guides/column-ordering-dnd.md +99 -0
- package/data/guides/column-pinning.md +72 -0
- package/data/guides/column-resizing.md +157 -0
- package/data/guides/column-size.md +162 -0
- package/data/guides/customize-components.md +395 -0
- package/data/guides/customize-icons.md +35 -0
- package/data/guides/data-columns.md +292 -0
- package/data/guides/density-toggle.md +46 -0
- package/data/guides/detail-panel.md +195 -0
- package/data/guides/display-columns.md +135 -0
- package/data/guides/editing.md +367 -0
- package/data/guides/expanding-sub-rows.md +194 -0
- package/data/guides/full-screen-toggle.md +63 -0
- package/data/guides/global-filtering.md +237 -0
- package/data/guides/localization.md +57 -0
- package/data/guides/memoization.md +157 -0
- package/data/guides/pagination.md +171 -0
- package/data/guides/row-actions.md +116 -0
- package/data/guides/row-numbers.md +24 -0
- package/data/guides/row-ordering-dnd.md +51 -0
- package/data/guides/row-pinning.md +96 -0
- package/data/guides/row-selection.md +237 -0
- package/data/guides/sorting.md +190 -0
- package/data/guides/state-management.md +165 -0
- package/data/guides/sticky-header.md +41 -0
- package/data/guides/table-event-listeners.md +103 -0
- package/data/guides/toolbar-customization.md +251 -0
- package/data/guides/virtualization.md +183 -0
- package/data/index.json +1930 -0
- package/data/reference/mrt-components.md +183 -0
- package/data/reference/mrt-hooks.md +125 -0
- package/data/skills/composable-components/SKILL.md +189 -0
- package/data/skills/customization/SKILL.md +190 -0
- package/data/skills/drag-and-drop-ordering/SKILL.md +227 -0
- package/data/skills/editing/SKILL.md +243 -0
- package/data/skills/filtering/SKILL.md +213 -0
- package/data/skills/getting-started/SKILL.md +213 -0
- package/data/skills/localization/SKILL.md +182 -0
- package/data/skills/migrate-v3-to-v4/SKILL.md +161 -0
- package/data/skills/state-and-server-data/SKILL.md +200 -0
- package/data/skills/virtualization/SKILL.md +203 -0
- package/dist/data.js +137 -0
- package/dist/index.js +232 -0
- package/package.json +50 -0
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import { lazy, Suspense, useMemo, useState } from 'react';
|
|
2
|
+
import {
|
|
3
|
+
MaterialReactTable,
|
|
4
|
+
// createRow,
|
|
5
|
+
type MRT_ColumnDef,
|
|
6
|
+
type MRT_Row,
|
|
7
|
+
type MRT_TableOptions,
|
|
8
|
+
useMaterialReactTable,
|
|
9
|
+
} from 'material-react-table';
|
|
10
|
+
import {
|
|
11
|
+
Box,
|
|
12
|
+
Button,
|
|
13
|
+
CircularProgress,
|
|
14
|
+
IconButton,
|
|
15
|
+
Tooltip,
|
|
16
|
+
Typography,
|
|
17
|
+
} from '@mui/material';
|
|
18
|
+
import {
|
|
19
|
+
QueryClient,
|
|
20
|
+
QueryClientProvider,
|
|
21
|
+
useMutation,
|
|
22
|
+
useQuery,
|
|
23
|
+
useQueryClient,
|
|
24
|
+
} from '@tanstack/react-query';
|
|
25
|
+
import { type User, fakeData, usStates } from './makeData';
|
|
26
|
+
import EditIcon from '@mui/icons-material/Edit';
|
|
27
|
+
import DeleteIcon from '@mui/icons-material/Delete';
|
|
28
|
+
|
|
29
|
+
const Example = () => {
|
|
30
|
+
const [validationErrors, setValidationErrors] = useState<
|
|
31
|
+
Record<string, string | undefined>
|
|
32
|
+
>({});
|
|
33
|
+
//keep track of rows that have been edited
|
|
34
|
+
const [editedUsers, setEditedUsers] = useState<Record<string, User>>({});
|
|
35
|
+
|
|
36
|
+
const columns = useMemo<MRT_ColumnDef<User>[]>(
|
|
37
|
+
() => [
|
|
38
|
+
{
|
|
39
|
+
accessorKey: 'id',
|
|
40
|
+
header: 'Id',
|
|
41
|
+
enableEditing: false,
|
|
42
|
+
size: 80,
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
accessorKey: 'firstName',
|
|
46
|
+
header: 'First Name',
|
|
47
|
+
muiEditTextFieldProps: ({ cell, row }) => ({
|
|
48
|
+
type: 'text',
|
|
49
|
+
required: true,
|
|
50
|
+
error: !!validationErrors?.[cell.id],
|
|
51
|
+
helperText: validationErrors?.[cell.id],
|
|
52
|
+
//store edited user in state to be saved later
|
|
53
|
+
onBlur: (event) => {
|
|
54
|
+
const validationError = !validateRequired(event.currentTarget.value)
|
|
55
|
+
? 'Required'
|
|
56
|
+
: undefined;
|
|
57
|
+
setValidationErrors({
|
|
58
|
+
...validationErrors,
|
|
59
|
+
[cell.id]: validationError,
|
|
60
|
+
});
|
|
61
|
+
setEditedUsers({ ...editedUsers, [row.id]: row.original });
|
|
62
|
+
},
|
|
63
|
+
}),
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
accessorKey: 'lastName',
|
|
67
|
+
header: 'Last Name',
|
|
68
|
+
muiEditTextFieldProps: ({ cell, row }) => ({
|
|
69
|
+
type: 'text',
|
|
70
|
+
required: true,
|
|
71
|
+
error: !!validationErrors?.[cell.id],
|
|
72
|
+
helperText: validationErrors?.[cell.id],
|
|
73
|
+
//store edited user in state to be saved later
|
|
74
|
+
onBlur: (event) => {
|
|
75
|
+
const validationError = !validateRequired(event.currentTarget.value)
|
|
76
|
+
? 'Required'
|
|
77
|
+
: undefined;
|
|
78
|
+
setValidationErrors({
|
|
79
|
+
...validationErrors,
|
|
80
|
+
[cell.id]: validationError,
|
|
81
|
+
});
|
|
82
|
+
setEditedUsers({ ...editedUsers, [row.id]: row.original });
|
|
83
|
+
},
|
|
84
|
+
}),
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
accessorKey: 'email',
|
|
88
|
+
header: 'Email',
|
|
89
|
+
muiEditTextFieldProps: ({ cell, row }) => ({
|
|
90
|
+
type: 'email',
|
|
91
|
+
required: true,
|
|
92
|
+
error: !!validationErrors?.[cell.id],
|
|
93
|
+
helperText: validationErrors?.[cell.id],
|
|
94
|
+
//store edited user in state to be saved later
|
|
95
|
+
onBlur: (event) => {
|
|
96
|
+
const validationError = !validateEmail(event.currentTarget.value)
|
|
97
|
+
? 'Incorrect Email Format'
|
|
98
|
+
: undefined;
|
|
99
|
+
setValidationErrors({
|
|
100
|
+
...validationErrors,
|
|
101
|
+
[cell.id]: validationError,
|
|
102
|
+
});
|
|
103
|
+
setEditedUsers({ ...editedUsers, [row.id]: row.original });
|
|
104
|
+
},
|
|
105
|
+
}),
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
accessorKey: 'state',
|
|
109
|
+
header: 'State',
|
|
110
|
+
editVariant: 'select',
|
|
111
|
+
editSelectOptions: usStates,
|
|
112
|
+
muiEditTextFieldProps: ({ row }) => ({
|
|
113
|
+
select: true,
|
|
114
|
+
error: !!validationErrors?.state,
|
|
115
|
+
helperText: validationErrors?.state,
|
|
116
|
+
onChange: (event) =>
|
|
117
|
+
setEditedUsers({
|
|
118
|
+
...editedUsers,
|
|
119
|
+
[row.id]: { ...row.original, state: event.target.value },
|
|
120
|
+
}),
|
|
121
|
+
}),
|
|
122
|
+
},
|
|
123
|
+
],
|
|
124
|
+
[editedUsers, validationErrors],
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
//call CREATE hook
|
|
128
|
+
const { mutateAsync: createUser, isPending: isCreatingUser } =
|
|
129
|
+
useCreateUser();
|
|
130
|
+
//call READ hook
|
|
131
|
+
const {
|
|
132
|
+
data: fetchedUsers = [],
|
|
133
|
+
isError: isLoadingUsersError,
|
|
134
|
+
isFetching: isFetchingUsers,
|
|
135
|
+
isLoading: isLoadingUsers,
|
|
136
|
+
} = useGetUsers();
|
|
137
|
+
//call UPDATE hook
|
|
138
|
+
const { mutateAsync: updateUsers, isPending: isUpdatingUsers } =
|
|
139
|
+
useUpdateUsers();
|
|
140
|
+
//call DELETE hook
|
|
141
|
+
const { mutateAsync: deleteUser, isPending: isDeletingUser } =
|
|
142
|
+
useDeleteUser();
|
|
143
|
+
|
|
144
|
+
//CREATE action
|
|
145
|
+
const handleCreateUser: MRT_TableOptions<User>['onCreatingRowSave'] = async ({
|
|
146
|
+
values,
|
|
147
|
+
table,
|
|
148
|
+
}) => {
|
|
149
|
+
const newValidationErrors = validateUser(values);
|
|
150
|
+
if (Object.values(newValidationErrors).some((error) => error)) {
|
|
151
|
+
setValidationErrors(newValidationErrors);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
setValidationErrors({});
|
|
155
|
+
await createUser(values);
|
|
156
|
+
table.setCreatingRow(null); //exit creating mode
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
//UPDATE action
|
|
160
|
+
const handleSaveUsers = async () => {
|
|
161
|
+
if (Object.values(validationErrors).some((error) => !!error)) return;
|
|
162
|
+
await updateUsers(Object.values(editedUsers));
|
|
163
|
+
setEditedUsers({});
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
//DELETE action
|
|
167
|
+
const openDeleteConfirmModal = (row: MRT_Row<User>) => {
|
|
168
|
+
if (window.confirm('Are you sure you want to delete this user?')) {
|
|
169
|
+
deleteUser(row.original.id);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const table = useMaterialReactTable({
|
|
174
|
+
columns,
|
|
175
|
+
data: fetchedUsers,
|
|
176
|
+
createDisplayMode: 'row', // ('modal', and 'custom' are also available)
|
|
177
|
+
editDisplayMode: 'cell', // ('modal', 'row', 'table', and 'custom' are also available)
|
|
178
|
+
enableCellActions: true,
|
|
179
|
+
enableClickToCopy: 'context-menu',
|
|
180
|
+
enableColumnPinning: true,
|
|
181
|
+
enableEditing: true,
|
|
182
|
+
enableRowActions: true,
|
|
183
|
+
getRowId: (row) => row.id,
|
|
184
|
+
muiToolbarAlertBannerProps: isLoadingUsersError
|
|
185
|
+
? {
|
|
186
|
+
color: 'error',
|
|
187
|
+
children: 'Error loading data',
|
|
188
|
+
}
|
|
189
|
+
: undefined,
|
|
190
|
+
muiTableContainerProps: {
|
|
191
|
+
sx: {
|
|
192
|
+
minHeight: '500px',
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
onCreatingRowCancel: () => setValidationErrors({}),
|
|
196
|
+
onCreatingRowSave: handleCreateUser,
|
|
197
|
+
renderRowActions: ({ row }) => (
|
|
198
|
+
<Box sx={{ display: 'flex', gap: '1rem' }}>
|
|
199
|
+
<Tooltip title="Delete">
|
|
200
|
+
<IconButton color="error" onClick={() => openDeleteConfirmModal(row)}>
|
|
201
|
+
<DeleteIcon />
|
|
202
|
+
</IconButton>
|
|
203
|
+
</Tooltip>
|
|
204
|
+
</Box>
|
|
205
|
+
),
|
|
206
|
+
renderBottomToolbarCustomActions: () => (
|
|
207
|
+
<Box sx={{ display: 'flex', gap: '1rem', alignItems: 'center' }}>
|
|
208
|
+
<Button
|
|
209
|
+
color="success"
|
|
210
|
+
variant="contained"
|
|
211
|
+
onClick={handleSaveUsers}
|
|
212
|
+
disabled={
|
|
213
|
+
Object.keys(editedUsers).length === 0 ||
|
|
214
|
+
Object.values(validationErrors).some((error) => !!error)
|
|
215
|
+
}
|
|
216
|
+
>
|
|
217
|
+
{isUpdatingUsers ? <CircularProgress size={25} /> : 'Save'}
|
|
218
|
+
</Button>
|
|
219
|
+
{Object.values(validationErrors).some((error) => !!error) && (
|
|
220
|
+
<Typography color="error">Fix errors before submitting</Typography>
|
|
221
|
+
)}
|
|
222
|
+
</Box>
|
|
223
|
+
),
|
|
224
|
+
renderTopToolbarCustomActions: ({ table }) => (
|
|
225
|
+
<Button
|
|
226
|
+
variant="contained"
|
|
227
|
+
onClick={() => {
|
|
228
|
+
table.setCreatingRow(true); //simplest way to open the create row modal with no default values
|
|
229
|
+
//or you can pass in a row object to set default values with the `createRow` helper function
|
|
230
|
+
// table.setCreatingRow(
|
|
231
|
+
// createRow(table, {
|
|
232
|
+
// //optionally pass in default values for the new row, useful for nested data or other complex scenarios
|
|
233
|
+
// }),
|
|
234
|
+
// );
|
|
235
|
+
}}
|
|
236
|
+
>
|
|
237
|
+
Create New User
|
|
238
|
+
</Button>
|
|
239
|
+
),
|
|
240
|
+
initialState: {
|
|
241
|
+
columnPinning: {
|
|
242
|
+
end: ['mrt-row-actions'],
|
|
243
|
+
start: [],
|
|
244
|
+
},
|
|
245
|
+
},
|
|
246
|
+
state: {
|
|
247
|
+
isLoading: isLoadingUsers,
|
|
248
|
+
isSaving: isCreatingUser || isUpdatingUsers || isDeletingUser,
|
|
249
|
+
showAlertBanner: isLoadingUsersError,
|
|
250
|
+
showProgressBars: isFetchingUsers,
|
|
251
|
+
},
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
return <MaterialReactTable table={table} />;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
//CREATE hook (post new user to api)
|
|
258
|
+
function useCreateUser() {
|
|
259
|
+
const queryClient = useQueryClient();
|
|
260
|
+
return useMutation({
|
|
261
|
+
mutationFn: async (user: User) => {
|
|
262
|
+
//send api update request here
|
|
263
|
+
await new Promise((resolve) => setTimeout(resolve, 1000)); //fake api call
|
|
264
|
+
return Promise.resolve();
|
|
265
|
+
},
|
|
266
|
+
//client side optimistic update
|
|
267
|
+
onMutate: (newUserInfo: User) => {
|
|
268
|
+
queryClient.setQueryData(
|
|
269
|
+
['users'],
|
|
270
|
+
(prevUsers: any) =>
|
|
271
|
+
[
|
|
272
|
+
...prevUsers,
|
|
273
|
+
{
|
|
274
|
+
...newUserInfo,
|
|
275
|
+
id: (Math.random() + 1).toString(36).substring(7),
|
|
276
|
+
},
|
|
277
|
+
] as User[],
|
|
278
|
+
);
|
|
279
|
+
},
|
|
280
|
+
// onSettled: () => queryClient.invalidateQueries({ queryKey: ['users'] }), //refetch users after mutation, disabled for demo
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
//READ hook (get users from api)
|
|
285
|
+
function useGetUsers() {
|
|
286
|
+
return useQuery<User[]>({
|
|
287
|
+
queryKey: ['users'],
|
|
288
|
+
queryFn: async () => {
|
|
289
|
+
//send api request here
|
|
290
|
+
await new Promise((resolve) => setTimeout(resolve, 1000)); //fake api call
|
|
291
|
+
return Promise.resolve(fakeData);
|
|
292
|
+
},
|
|
293
|
+
refetchOnWindowFocus: false,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
//UPDATE hook (put user in api)
|
|
298
|
+
function useUpdateUsers() {
|
|
299
|
+
const queryClient = useQueryClient();
|
|
300
|
+
return useMutation({
|
|
301
|
+
mutationFn: async (users: User[]) => {
|
|
302
|
+
//send api update request here
|
|
303
|
+
await new Promise((resolve) => setTimeout(resolve, 1000)); //fake api call
|
|
304
|
+
return Promise.resolve();
|
|
305
|
+
},
|
|
306
|
+
//client side optimistic update
|
|
307
|
+
onMutate: (newUsers: User[]) => {
|
|
308
|
+
queryClient.setQueryData(['users'], (prevUsers: any) =>
|
|
309
|
+
prevUsers?.map((user: User) => {
|
|
310
|
+
const newUser = newUsers.find((u) => u.id === user.id);
|
|
311
|
+
return newUser ? newUser : user;
|
|
312
|
+
}),
|
|
313
|
+
);
|
|
314
|
+
},
|
|
315
|
+
// onSettled: () => queryClient.invalidateQueries({ queryKey: ['users'] }), //refetch users after mutation, disabled for demo
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
//DELETE hook (delete user in api)
|
|
320
|
+
function useDeleteUser() {
|
|
321
|
+
const queryClient = useQueryClient();
|
|
322
|
+
return useMutation({
|
|
323
|
+
mutationFn: async (userId: string) => {
|
|
324
|
+
//send api update request here
|
|
325
|
+
await new Promise((resolve) => setTimeout(resolve, 1000)); //fake api call
|
|
326
|
+
return Promise.resolve();
|
|
327
|
+
},
|
|
328
|
+
//client side optimistic update
|
|
329
|
+
onMutate: (userId: string) => {
|
|
330
|
+
queryClient.setQueryData(['users'], (prevUsers: any) =>
|
|
331
|
+
prevUsers?.filter((user: User) => user.id !== userId),
|
|
332
|
+
);
|
|
333
|
+
},
|
|
334
|
+
// onSettled: () => queryClient.invalidateQueries({ queryKey: ['users'] }), //refetch users after mutation, disabled for demo
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
//react query setup in App.tsx
|
|
339
|
+
const ReactQueryDevtoolsProduction = lazy(() =>
|
|
340
|
+
import('@tanstack/react-query-devtools/build/modern/production.js').then(
|
|
341
|
+
(d) => ({
|
|
342
|
+
default: d.ReactQueryDevtools,
|
|
343
|
+
}),
|
|
344
|
+
),
|
|
345
|
+
);
|
|
346
|
+
|
|
347
|
+
const queryClient = new QueryClient();
|
|
348
|
+
|
|
349
|
+
export default function App() {
|
|
350
|
+
return (
|
|
351
|
+
<QueryClientProvider client={queryClient}>
|
|
352
|
+
<Example />
|
|
353
|
+
<Suspense fallback={null}>
|
|
354
|
+
<ReactQueryDevtoolsProduction />
|
|
355
|
+
</Suspense>
|
|
356
|
+
</QueryClientProvider>
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const validateRequired = (value: string) => !!value.length;
|
|
361
|
+
const validateEmail = (email: string) =>
|
|
362
|
+
!!email.length &&
|
|
363
|
+
email
|
|
364
|
+
.toLowerCase()
|
|
365
|
+
.match(
|
|
366
|
+
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
|
|
367
|
+
);
|
|
368
|
+
|
|
369
|
+
function validateUser(user: User) {
|
|
370
|
+
return {
|
|
371
|
+
firstName: !validateRequired(user.firstName)
|
|
372
|
+
? 'First Name is Required'
|
|
373
|
+
: '',
|
|
374
|
+
lastName: !validateRequired(user.lastName) ? 'Last Name is Required' : '',
|
|
375
|
+
email: !validateEmail(user.email) ? 'Incorrect Email Format' : '',
|
|
376
|
+
};
|
|
377
|
+
}
|