From b66db88aa54800452e5fc0183fe44ba334a67d32 Mon Sep 17 00:00:00 2001 From: Sterling Camden Date: Mon, 16 Dec 2024 13:14:27 -1000 Subject: [PATCH] Update use-debounced-callback.ts to add a flush method to the returned callback as well as give an option to simply flush on unmount --- .../use-debounced-callback.ts | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/@mantine/hooks/src/use-debounced-callback/use-debounced-callback.ts b/packages/@mantine/hooks/src/use-debounced-callback/use-debounced-callback.ts index a0089afc6ee..38589a34161 100644 --- a/packages/@mantine/hooks/src/use-debounced-callback/use-debounced-callback.ts +++ b/packages/@mantine/hooks/src/use-debounced-callback/use-debounced-callback.ts @@ -1,19 +1,36 @@ import { useCallback, useEffect, useRef } from 'react'; import { useCallbackRef } from '../use-callback-ref/use-callback-ref'; -export function useDebouncedCallback any>( +export function useDebounceCallback any>( callback: T, - delay: number + options: number | { delay: number; flushOnUnmount?: boolean }, ) { + const delay = typeof options === 'number' ? options : options.delay; + const flushOnUnmount = typeof options === 'number' ? false : options.flushOnUnmount; const handleCallback = useCallbackRef(callback); const debounceTimerRef = useRef(0); - useEffect(() => () => window.clearTimeout(debounceTimerRef.current), []); - return useCallback( + const lastCallback: ((...args: Parameters) => void) & { + flush?: () => void; + } = useCallback( (...args: Parameters) => { window.clearTimeout(debounceTimerRef.current); - debounceTimerRef.current = window.setTimeout(() => handleCallback(...args), delay); + const flush = () => handleCallback(...args); + lastCallback.flush = flush; + debounceTimerRef.current = window.setTimeout(flush, delay); }, - [handleCallback, delay] + [handleCallback, delay], ); + + useEffect( + () => () => { + window.clearTimeout(debounceTimerRef.current); + if (flushOnUnmount) { + lastCallback.flush?.(); + } + }, + [lastCallback, flushOnUnmount], + ); + + return lastCallback; }