Skip to content

Commit

Permalink
Merge pull request #109 from astahmer/fix/stale-page-size
Browse files Browse the repository at this point in the history
fix: stale pageSize cause of missing useEffect deps
  • Loading branch information
Kuechlin authored Oct 14, 2022
2 parents f0969be + 068f891 commit e334641
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 25 deletions.
1 change: 1 addition & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module.exports = {
'plugin:@typescript-eslint/recommended',
'plugin:import/recommended',
'plugin:import/typescript',
'plugin:react-hooks/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
Expand Down
3 changes: 1 addition & 2 deletions docs/pages/Filters.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Stack, Table, Title, Text, createStyles, Group, SimpleGrid, Card, Divider } from '@mantine/core';
import { Card, Divider, Stack, Title } from '@mantine/core';
import { Prism } from '@mantine/prism';
import { Fragment } from 'react';
import { PropertyTable } from '../components/PropertyTable';

export default function Filters() {
Expand Down
2 changes: 1 addition & 1 deletion docs/pages/examples/AsyncExample.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default function AsyncExample() {

useEffect(() => {
load({ pageIndex: 0, pageSize: 10 });
}, []);
});

return (
<DataGrid<Data>
Expand Down
54 changes: 54 additions & 0 deletions docs/pages/examples/MinimalExample.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Button } from '@mantine/core';
import { useState } from 'react';
import { DataGrid } from '../../../src';
import { Data, demoData } from '../../demoData';

type FetchResponse = {
list: Data[];
total: number;
};

function fetchData(page: number, pageSize: number, search: string): Promise<FetchResponse> {
return new Promise((resolve) =>
setTimeout(() => {
const data = demoData.filter(
(x) => x.text.includes(search) || x.cat.includes(search) || x.fish.includes(search) || x.city.includes(search)
);
resolve({
list: data.slice(page * pageSize, page * pageSize + pageSize),
total: data.length + 2,
});
}, 1000)
);
}

export default function MinimalExample() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState<FetchResponse>({ list: [], total: 0 });
console.log({ loading }, data);

return (
<>
<Button
onClick={async () => {
setLoading(true);
const res = await fetchData(0, 100, '');
setData(res);
setLoading(false);
}}
>
Fetch data
</Button>
<DataGrid
data={data.list}
columns={[
{ header: 'cat', accessorFn: (row) => row.cat },
{ header: 'fish', accessorFn: (row) => row.fish },
{ header: 'city', accessorFn: (row) => row.city },
{ header: 'value', accessorFn: (row) => row.value },
]}
loading={loading}
/>
</>
);
}
10 changes: 10 additions & 0 deletions docs/pages/examples/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ import LocaleExample from './LocaleExample';
// @ts-ignore
import LocaleExampleCode from './LocaleExample.tsx?raw';

import MinimalExample from './MinimalExample';
// @ts-ignore
import MinimalExampleCode from './MinimalExample.tsx?raw';

import OnRowClickExample from './OnRowExample';
// @ts-ignore
import OnRowClickExampleCode from './OnRowExample.tsx?raw';
Expand Down Expand Up @@ -62,6 +66,12 @@ export const examples = {
element: DefaultExample,
code: DefaultExampleCode,
}),
minimal: ex({
label: 'Minimal example',
path: '/example/minimal',
element: MinimalExample,
code: MinimalExampleCode,
}),
customFilter: ex({
label: 'Custom Filter',
path: '/example/custom-filter',
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mantine-data-grid",
"version": "0.0.19",
"version": "0.0.20",
"homepage": "https://kuechlin.github.io/mantine-data-grid/",
"repository": {
"type": "git",
Expand Down Expand Up @@ -57,6 +57,7 @@
"eslint-import-resolver-typescript": "^3.5.1",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react-hooks": "^4.6.0",
"husky": "^8.0.1",
"lint-staged": "^13.0.3",
"prettier": "^2.7.1",
Expand Down
19 changes: 15 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 17 additions & 15 deletions src/DataGrid.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { RefCallback, useCallback, useEffect, useImperativeHandle, useState } from 'react';
import { LoadingOverlay, ScrollArea, Stack, Table as MantineTable, Text } from '@mantine/core';
import {
ColumnFiltersState,
Expand All @@ -10,22 +9,23 @@ import {
getSortedRowModel,
OnChangeFn,
PaginationState,
SortingState,
useReactTable,
RowData,
RowSelectionState,
SortingState,
Table,
useReactTable,
} from '@tanstack/react-table';
import { RefCallback, useCallback, useEffect, useImperativeHandle, useState } from 'react';
import { BoxOff } from 'tabler-icons-react';

import useStyles from './DataGrid.styles';

import { GlobalFilter, globalFilterFn } from './GlobalFilter';
import { ColumnSorter } from './ColumnSorter';
import { ColumnFilter } from './ColumnFilter';
import { ColumnSorter } from './ColumnSorter';
import { GlobalFilter, globalFilterFn } from './GlobalFilter';
import { DEFAULT_INITIAL_SIZE, Pagination } from './Pagination';
import { DataGridProps } from './types';
import { getRowSelectionColumn } from './RowSelection';
import { DataGridProps } from './types';

export function useDataGrid<TData extends RowData>(): [Table<TData> | null, RefCallback<Table<TData>>] {
const [state, setState] = useState<Table<TData> | null>(null);
Expand Down Expand Up @@ -125,15 +125,17 @@ export function DataGrid<TData extends RowData>({
});
useImperativeHandle(tableRef, () => table);

const tableSize = table.getTotalSize();

useEffect(() => {
if (noFlexLayout) {
setTableWidth(table.getTotalSize() + 'px');
setTableWidth(tableSize + 'px');
} else if (width) {
setTableWidth(width + 'px');
} else {
setTableWidth('100%');
}
}, [width, noFlexLayout, table.getTotalSize()]);
}, [table, width, noFlexLayout, tableSize]);

const handleGlobalFilterChange: OnChangeFn<string> = useCallback(
(arg0) =>
Expand All @@ -145,7 +147,7 @@ export function DataGrid<TData extends RowData>({
globalFilter: next,
};
}),
[onSearch]
[table, onSearch]
);

const handleSortingChange: OnChangeFn<SortingState> = useCallback(
Expand All @@ -158,7 +160,7 @@ export function DataGrid<TData extends RowData>({
sorting: next,
};
}),
[onSort]
[table, onSort]
);

const handleColumnFiltersChange: OnChangeFn<ColumnFiltersState> = useCallback(
Expand All @@ -171,7 +173,7 @@ export function DataGrid<TData extends RowData>({
columnFilters: next,
};
}),
[onFilter]
[table, onFilter]
);

const handlePaginationChange: OnChangeFn<PaginationState> = useCallback(
Expand All @@ -186,7 +188,7 @@ export function DataGrid<TData extends RowData>({
}));
}
},
[onPageChange]
[table, onPageChange]
);

const handleRowSelectionChange: OnChangeFn<RowSelectionState> = useCallback(
Expand All @@ -200,7 +202,7 @@ export function DataGrid<TData extends RowData>({
};
});
},
[onRowSelectionChange]
[table, onRowSelectionChange]
);

const pageCount = withPagination && total ? Math.ceil(total / table.getState().pagination.pageSize) : undefined;
Expand All @@ -217,11 +219,11 @@ export function DataGrid<TData extends RowData>({

useEffect(() => {
if (withPagination) {
table.setPageSize(initialState?.pagination?.pageSize || DEFAULT_INITIAL_SIZE);
table.setPageSize(initialState?.pagination?.pageSize ?? DEFAULT_INITIAL_SIZE);
} else {
table.setPageSize(data.length);
}
}, [withPagination]);
}, [table, withPagination, data.length, initialState?.pagination?.pageSize]);

return (
<Stack {...others} spacing={verticalSpacing} className={classes.wrapper}>
Expand Down
2 changes: 1 addition & 1 deletion src/GlobalFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function GlobalFilter<TData>({ table, className, locale }: GlobalFilterPr
}, 200);

return () => clearTimeout(timeout);
}, [value]);
}, [table, value]);

return (
<TextInput
Expand Down
2 changes: 1 addition & 1 deletion src/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Group, Select, Text, Pagination as MantinePagination, Box, MantineNumberSize } from '@mantine/core';
import { Box, Group, MantineNumberSize, Pagination as MantinePagination, Select, Text } from '@mantine/core';
import { Table } from '@tanstack/react-table';
import { DataGridLocale, PaginationMode } from './types';

Expand Down

0 comments on commit e334641

Please sign in to comment.