0

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
A.Usama
  • 157
  • 2
  • 8
  • Have you tried separating the sidebar filters logic to a different "useEffect" callback? After all, There is not a limitation to use a single useEffect :) – Drago96 Apr 21 '22 at 11:31
  • 3
    The effect runs every time `totalProducts` changes, and the effect changes `totalProducts`, which creates an infinite loop. This may be a good time to take a step back, because it looks like you may be over-complicating pagination logic and storing things in state which don't need to be in state. If you already have the entire list of data client-side and just want to display a filtered/paged subset of that data, you don't need to keep that subset in state. Just the filtering/paging values. Use those values to filter the data before displaying it. – David Apr 21 '22 at 11:31

0 Answers0