UNPKG

@ackplus/react-tanstack-data-table

Version:

A powerful React data table component built with MUI and TanStack Table

49 lines (48 loc) 1.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useDebouncedFetch = useDebouncedFetch; const react_1 = require("react"); function useDebouncedFetch(onFetchData, delay = 300) { const [isLoading, setIsLoading] = (0, react_1.useState)(false); const debounceTimer = (0, react_1.useRef)(null); const debouncedFetch = (0, react_1.useCallback)(async (filters) => { if (!onFetchData) return null; // Create a unique key for the current fetch parameters // const currentParams = JSON.stringify(filters); // Clear existing timer if (debounceTimer.current) { clearTimeout(debounceTimer.current); } return new Promise((resolve) => { debounceTimer.current = setTimeout(async () => { setIsLoading(true); try { const result = await onFetchData(filters); resolve(result); } catch (error) { // Handle fetch error silently or could be passed to onError callback console.error('Error fetching data:', error); resolve(null); } finally { setIsLoading(false); } }, delay); }); }, [onFetchData, delay]); // Cleanup timer on unmount (0, react_1.useEffect)(() => { // Fetch data when dependencies change return () => { if (debounceTimer.current) { clearTimeout(debounceTimer.current); } }; }, []); return { debouncedFetch, isLoading, }; }