79259529

Date: 2024-12-06 22:23:49
Score: 0.5
Natty:
Report link

I have found an acceptable solution (after days of error).

I think the question refers to something similar to the pro version of mui Infinite loading

However I have found a way to do it with the community version.

Version of data grid used: “@mui/x-data-grid”: “^7.22.2”

I have created a custom hook to do the same functionality

// useTableScrollInfinitie.tsx
import { useGridApiRef } from "@mui/x-data-grid";
import { useEffect, useRef } from "react";

interface IProps {
  isLoading: boolean;
  onNextPage: () => void;
  threshold?: number;
}

export const useTableScrollInfinitie = ({ onNextPage, isLoading, threshold = 0 }: IProps) => {
  const gridApiRef = useGridApiRef();
  const scrollMonitor = useRef<Function | null>(null);

  useEffect(() => {
    if (gridApiRef.current?.instanceId) {
      // Obtenemos el elementScroll
      const elementScroll =
        gridApiRef.current.rootElementRef.current?.children[0].children[1];

      // Suscripción al evento scrollPositionChange si no está cargando datos
      if (!isLoading && elementScroll) {
        scrollMonitor.current = gridApiRef.current.subscribeEvent(
          "scrollPositionChange",
          (event) => {
            const maxScrollTop =
              elementScroll.scrollHeight - elementScroll.clientHeight;
            const scrollThreshold = maxScrollTop * (1 - threshold / 100);

            if (event.top >= scrollThreshold) {
              onNextPage();
            }
          }
        );
      }
    }

    // Cleanup al desmontar el componente o cambiar dependencias
    return () => {
      if (scrollMonitor.current) {
        scrollMonitor.current();
      }
    };
  }, [gridApiRef, isLoading]);

  return { gridApiRef };
};

Using it is really simple

 const { gridApiRef } = useTableScrollInfinitie({
    isLoading: isFetching, // api rest fetching
    threshold: 0, // fetch data when scroll to bottom
    onNextPage: () => {
      // fetch more data
    },
  });

and “gridApiRef” we will pass it as props to

  <DataGrid
        apiRef={gridApiRef}
       ...
      />

Here is a little demo

Demo infinite-loading

Reasons:
  • Blacklisted phrase (1): está
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: fabjiro