I'm trying to create the pagination logic with filtering but When I try to change the state setTotalProducts
at useEffect
it throws the warning of maximum update depth exceeded at any case totalProducts
is in the deps array.
const [totalProducts, setTotalProducts] = useState(products); // products is a previously fetched data
const [filteredProducts, setFilteredProducts] = useState(totalProducts);
const productsPerPage = 9;
const indexOfLastProduct = currentPage * productsPerPage;
const indexOfFirstProduct = indexOfLastProduct - productsPerPage;
useEffect(() => {
setFilteredProducts(
totalProducts.slice(indexOfFirstProduct, indexOfLastProduct)
);
// Sidebar filters
if (Object.entries(filters).length > 0) {
const arr = filterSidebar(products, filters); // returns an array of filtered data
setTotalProducts(arr); // Setting this state causes the problem
}
}, [filters, currentPage, totalProducts]); // It won't work as expected in case of removing totalProducts