I have a component that creates a react table which works as expected when there is just one page involved:
const ReactTable = (props) => {
const {data, columns, viewState, updateViewState} = props;
const defaultColumn = React.useMemo(() => ({
Filter: DefaultColumnFilter,
updateFiltering: (column, newValue) => updateFiltering(viewState, updateViewState, column, newValue),
filter: 'standard',
canResize: true}),[]);
const {filters, filterable, groupBy, expanded, page} = viewState;
const tableInstance = useTable(
{
columns,
data,
defaultColumn,
autoResetExpanded: false,
groupByFn: (rows, columnId) => {
const getKey = value => value.label ? value.label: value;
return rows.reduce((prev, row) => {
const resKey = `${getKey(row.values[columnId])}`;
prev[resKey] = Array.isArray(prev[resKey]) ? prev[resKey] : [];
prev[resKey].push(row);
return prev}, {})},
filterTypes: {'standard': applyFilter},
pageSize: page.size,
initialState: {filters, groupBy, expanded, pageIndex: page.index}},
useFilters,
useGroupBy,
useExpanded,
usePagination,
useRowSelect,
addSelectColumn);
const {getTableProps, getTableBodyProps, setGroupBy} = tableInstance;
React.useEffect(
() => updateViewStateFromTable(viewState, tableInstance, updateViewState));
if (!isEqual(groupBy, tableInstance.state.groupBy)) setGroupBy(groupBy);
const headerRows = getHeaderRows(tableInstance, viewState, updateViewState);
const dataRows = getDataRows(tableInstance);
const filterRow = getFilterRow(tableInstance, viewState);
console.log('ReactTable', {props, tableInstance})
return (
<div>
<table className="ReactTable -highlight rt-table"
{...getTableProps()}>
<thead className="rt-thead -header">
{headerRows}
</thead>
<tbody className="rt-tbody" {...getTableBodyProps()}>
{(filterable)? filterRow:null}
{dataRows}
</tbody>
<PaginationFoot {...{viewState, tableInstance}} />
</table>
<h2>viewState:</h2>
<pre>
<code>
{JSON.stringify({viewState}, null, 4)}
</code>
</pre>
</div>)};
export default ReactTable;
Unfortunately, if I change the page index or size on one page, it affects all other pages as well.
The "viewState" is my construct used to track and persist the filter, pagination, expansion, column selection, grouping, and sorting (and to permit users to create their own custom named view states).
It appears that the internal state of the table is being destructively modified because the viewState copies show the correct pagination data (but are then updated to the incorrect shared values after render).
I tried using useControlledState to work directly into/out of the viewState but this causes errors because it is attempting to update the state during the render operation.