Skip to content

Instantly share code, notes, and snippets.

@zigcccc
Last active November 3, 2022 08:19
Show Gist options
  • Select an option

  • Save zigcccc/a945a47d28f6a573a731e6069cda5ef6 to your computer and use it in GitHub Desktop.

Select an option

Save zigcccc/a945a47d28f6a573a731e6069cda5ef6 to your computer and use it in GitHub Desktop.
Generic Pageable Table
/**
* The goal of this component is to:
* - render the table data
* - handle initial API call + any additional page and/or search related API calls
* - render table header & footer with pagination and actions
*/
const PageableTable = ({
columns,
components,
data,
filters,
hasError,
isLoading,
onFetchData,
onRowClick,
pagination,
tableProps: tablePropsBase,
title,
}) => {
const { values: params } = useFormState();
// Joined Table props
const tableProps = { ...tablePropsBase, columns, data, onRowClick };
const emptyResults = hasEmptyResults({ data, isLoading });
const emptySearchResults = hasEmptySearchResults({ data, isLoading, params });
// We are setting isSearching to true if we are in a loading state and the value
// for the search Query exists
const isSearching = isLoading && Boolean(params.searchKey);
// Props shared between all of the PageableTable child components
const commonProps = { isLoading, isSearching };
const handleRefresh = () => {
onFetchData({ page: pagination.currentPage, params });
};
const handleFetchPreviousPage = () => {
if (pagination.hasPreviousPage) {
onFetchData({ page: pagination.currentPage - 1, params });
}
};
const handleFetchNextPage = () => {
if (pagination.hasNextPage) {
onFetchData({ page: pagination.currentPage + 1, params });
}
};
return (
<div className="pageable-table">
<TableActionbar
{...commonProps}
filters={filters}
hasError={hasError}
onGoToNextPage={handleFetchNextPage}
onGoToPreviousPage={handleFetchPreviousPage}
onRefresh={handleRefresh}
pagination={pagination}
title={title}
/>
<PageableTableBody
{...commonProps}
{...tableProps}
components={components}
hasEmptyResults={emptyResults}
hasEmptySearchResults={emptySearchResults}
hasError={hasError}
onRefresh={handleRefresh}
params={params}
/>
<TableFooter
{...commonProps}
hasError={hasError}
onGoToNextPage={handleFetchNextPage}
onGoToPreviousPage={handleFetchPreviousPage}
pagination={pagination}
/>
</div>
);
};
const ProductsTable = ({ fetchProducts, products, ...rest }) => {
const history = useHistory();
const handleEditProductClick = (row) => {
history.push(getJoinedPath('products', row.original.id));
};
const columns = getProductsTableColumns({ onEditProduct: handleEditProductClick });
return (
<PageableTable
columns={columns}
components={{ ErrorState: ProductsTableErrorState, EmptyResults: ProductsTableEmptyState }}
data={products}
onFetchData={fetchProducts}
onRowClick={handleEditProductClick}
title="Seznam izdelkov"
{...rest}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment