-
-
Notifications
You must be signed in to change notification settings - Fork 535
Expand file tree
/
Copy pathTS.tsx
More file actions
225 lines (205 loc) · 6.81 KB
/
TS.tsx
File metadata and controls
225 lines (205 loc) · 6.81 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import {
type UIEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import {
MaterialReactTable,
useMaterialReactTable,
type MRT_ColumnDef,
type MRT_ColumnFiltersState,
type MRT_SortingState,
type MRT_RowVirtualizer,
} from 'material-react-table';
import { Typography } from '@mui/material';
import {
QueryClient,
QueryClientProvider,
useInfiniteQuery,
} from '@tanstack/react-query'; //Note: this is TanStack React Query V5
//Your API response shape will probably be different. Knowing a total row count is important though.
type UserApiResponse = {
data: Array<User>;
meta: {
totalRowCount: number;
};
};
type User = {
firstName: string;
lastName: string;
address: string;
state: string;
phoneNumber: string;
};
const columns: MRT_ColumnDef<User>[] = [
{
accessorKey: 'firstName',
header: 'First Name',
},
{
accessorKey: 'lastName',
header: 'Last Name',
},
{
accessorKey: 'address',
header: 'Address',
},
{
accessorKey: 'state',
header: 'State',
},
{
accessorKey: 'phoneNumber',
header: 'Phone Number',
},
];
const fetchSize = 25;
const Example = () => {
const tableContainerRef = useRef<HTMLDivElement>(null); //we can get access to the underlying TableContainer element and react to its scroll events
const rowVirtualizerInstanceRef = useRef<MRT_RowVirtualizer>(null); //we can get access to the underlying Virtualizer instance and call its scrollToIndex method
const [currentMaxPages, setCurrentMaxPages] = useState(4);
const [columnFilters, setColumnFilters] = useState<MRT_ColumnFiltersState>(
[],
);
const [globalFilter, setGlobalFilter] = useState<string>();
const [sorting, setSorting] = useState<MRT_SortingState>([]);
const { data, fetchNextPage, isError, isFetching, isLoading } =
useInfiniteQuery<UserApiResponse>({
queryKey: [
'table-data',
columnFilters, //refetch when columnFilters changes
globalFilter, //refetch when globalFilter changes
sorting, //refetch when sorting changes
],
queryFn: async ({ pageParam }) => {
const url = new URL(
'/api/data',
process.env.NODE_ENV === 'production'
? 'https://www.material-react-table.com'
: 'http://localhost:3000',
);
url.searchParams.set('start', `${(pageParam as number) * fetchSize}`);
url.searchParams.set('size', `${fetchSize}`);
url.searchParams.set('filters', JSON.stringify(columnFilters ?? []));
url.searchParams.set('globalFilter', globalFilter ?? '');
url.searchParams.set('sorting', JSON.stringify(sorting ?? []));
const response = await fetch(url.href);
const json = (await response.json()) as UserApiResponse;
return json;
},
initialPageParam: 0,
getNextPageParam: (_lastGroup, groups) => groups.length,
refetchOnWindowFocus: false,
maxPages: currentMaxPages,
});
const flatData = useMemo(
() => data?.pages.flatMap((page) => page.data) ?? [],
[data],
);
const totalDBRowCount = data?.pages?.[0]?.meta?.totalRowCount ?? 0;
const totalFetched = flatData.length;
const handleScroll = useCallback(() => {
const containerElement = tableContainerRef.current;
if (containerElement) {
const { scrollHeight, scrollTop, clientHeight } = containerElement;
if (
scrollHeight - scrollTop - clientHeight < 400 &&
!isFetching &&
totalFetched < totalDBRowCount &&
currentMaxPages < totalDBRowCount / fetchSize
) {
setCurrentMaxPages((prevMaxPages) => prevMaxPages + 2);
}
}
}, [currentMaxPages, isFetching, totalFetched, totalDBRowCount]);
//called on scroll and possibly on mount to fetch more data as the user scrolls and reaches bottom of table
const fetchMoreOnBottomReached = useCallback(
(containerRefElement?: HTMLDivElement | null) => {
if (containerRefElement) {
const { scrollHeight, scrollTop, clientHeight } = containerRefElement;
//once the user has scrolled within 400px of the bottom of the table, fetch more data if we can
if (
scrollHeight - scrollTop - clientHeight < 400 &&
!isFetching &&
totalFetched < totalDBRowCount
) {
fetchNextPage();
}
}
},
[fetchNextPage, isFetching, totalFetched, totalDBRowCount],
);
//scroll to top of table when sorting or filters change
useEffect(() => {
//scroll to the top of the table when the sorting changes
try {
rowVirtualizerInstanceRef.current?.scrollToIndex?.(0);
} catch (error) {
console.error(error);
}
}, [sorting, columnFilters, globalFilter]);
useEffect(() => {
const containerElement = tableContainerRef.current;
if (containerElement) {
containerElement.addEventListener('scroll', handleScroll);
return () => {
containerElement.removeEventListener('scroll', handleScroll);
};
}
}, [handleScroll]);
//a check on mount to see if the table is already scrolled to the bottom and immediately needs to fetch more data
useEffect(() => {
fetchMoreOnBottomReached(tableContainerRef.current);
}, [fetchMoreOnBottomReached]);
const table = useMaterialReactTable({
columns,
data: flatData,
enablePagination: false,
enableRowNumbers: true,
enableRowVirtualization: true,
manualFiltering: true,
manualSorting: true,
muiTableContainerProps: {
ref: tableContainerRef, //get access to the table container element
sx: { maxHeight: '600px' }, //give the table a max height
onScroll: (event: UIEvent<HTMLDivElement>) =>
fetchMoreOnBottomReached(event.target as HTMLDivElement), //add an event listener to the table container element
},
muiToolbarAlertBannerProps: isError
? {
color: 'error',
children: 'Error loading data',
}
: undefined,
onColumnFiltersChange: setColumnFilters,
onGlobalFilterChange: setGlobalFilter,
onSortingChange: setSorting,
renderBottomToolbarCustomActions: () => (
<Typography>
Fetched {totalFetched} of {totalDBRowCount} total rows.
</Typography>
),
state: {
columnFilters,
globalFilter,
isLoading,
showAlertBanner: isError,
showProgressBars: isFetching,
sorting,
},
rowVirtualizerInstanceRef, //get access to the virtualizer instance
rowVirtualizerOptions: { overscan: 4 },
});
return <MaterialReactTable table={table} />;
};
const queryClient = new QueryClient();
const ExampleWithReactQueryProvider = () => (
//App.tsx or AppProviders file. Don't just wrap this component with QueryClientProvider! Wrap your whole App!
<QueryClientProvider client={queryClient}>
<Example />
</QueryClientProvider>
);
export default ExampleWithReactQueryProvider;