'React useMemo - how to filter and paginate products
I am trying to filter and paginate products in an array of products from Airtable. I have the pagination working as expected. On page one of the paginated products the filters work as expected. As, in the filtered products are display on the page with pagination.

On page ONE of the paginated products the filters continue to work as expected. However on any other page when a filter is chosen the app breaks. The app shows the pagination component but not the filtered products.

I am not sure how to refactor the code so that the pagination component correctly displays the filtered array of products on the page.
I think I have to pass the filtered array of products to the pagination but have no idea what the would look like.
Any help is much appreciated.
import { useFilterContext } from "../context/filter_context";
import Stickers from "./Stickers";
import Pagination from "./Pagination";
let PageSize = 21;
const ProductList = () => {
const { filtered_products: products } = useFilterContext();
const [currentPage, setCurrentPage] = useState(1);
const currentProducts = useMemo(() => {
const firstPageIndex = (currentPage - 1) * PageSize;
const lastPageIndex = firstPageIndex + PageSize;
return products.slice(firstPageIndex, lastPageIndex);
}, [currentPage, products]);
if (products.length < 1) {
return (
<h5 style={{ textTransform: "none" }}>
Sorry, no stickers matched your search.
</h5>
);
}
return (
<>
<Stickers products={currentProducts} />
<Pagination
className="pagination-bar"
currentPage={currentPage}
totalProducts={products.length}
pageSize={PageSize}
onPageChange={(page) => setCurrentPage(page)}
/>
</>
);
};
export default ProductList;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
