From 087ebda5a85148dec5cb79c4abfa1d32b8a2a566 Mon Sep 17 00:00:00 2001 From: Tom Picton Date: Wed, 30 Aug 2023 14:45:04 -0400 Subject: [PATCH] Customizable useSelect input debounce wait --- src/hooks/useSelect/index.js | 25 +++++++++++++++---------- src/hooks/useSelect/utils.ts | 2 ++ typings/index.d.ts | 1 + 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/hooks/useSelect/index.js b/src/hooks/useSelect/index.js index f83727c4..1c6cc60b 100644 --- a/src/hooks/useSelect/index.js +++ b/src/hooks/useSelect/index.js @@ -40,6 +40,7 @@ function useSelect(userProps = {}) { itemToString, getA11ySelectionMessage, getA11yStatusMessage, + inputCleanupDebounceWait, } = props // Initial state depending on controlled props. const initialState = getInitialState(props) @@ -108,19 +109,23 @@ function useSelect(userProps = {}) { // Sets cleanup for the keysSoFar callback, debounded after 500ms. useEffect(() => { - // init the clean function here as we need access to dispatch. - clearTimeoutRef.current = debounce(outerDispatch => { - outerDispatch({ - type: stateChangeTypes.FunctionSetInputValue, - inputValue: '', - }) - }, 500) + if (inputCleanupDebounceWait > 0) { + // init the clean function here as we need access to dispatch. + clearTimeoutRef.current = debounce(outerDispatch => { + outerDispatch({ + type: stateChangeTypes.FunctionSetInputValue, + inputValue: '', + }) + }, inputCleanupDebounceWait) + } else { + clearTimeoutRef.current = null; + } // Cancel any pending debounced calls on mount return () => { - clearTimeoutRef.current.cancel() + clearTimeoutRef?.current.cancel() } - }, []) + }, [inputCleanupDebounceWait]) // Invokes the keysSoFar callback set up above. useEffect(() => { @@ -128,7 +133,7 @@ function useSelect(userProps = {}) { return } - clearTimeoutRef.current(dispatch) + clearTimeoutRef.current?.(dispatch) }, [dispatch, inputValue]) useControlPropsValidator({ diff --git a/src/hooks/useSelect/utils.ts b/src/hooks/useSelect/utils.ts index 6c7dd6d4..d38a4ec3 100644 --- a/src/hooks/useSelect/utils.ts +++ b/src/hooks/useSelect/utils.ts @@ -41,6 +41,7 @@ const propTypes = { items: PropTypes.array.isRequired, isItemDisabled: PropTypes.func, getA11ySelectionMessage: PropTypes.func, + inputCleanupDebounceWait: PropTypes.number, } /** @@ -79,6 +80,7 @@ export const defaultProps = { isItemDisabled() { return false }, + inputCleanupDebounceWait: 500, } // eslint-disable-next-line import/no-mutable-exports diff --git a/typings/index.d.ts b/typings/index.d.ts index 56efa400..8c24d580 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -366,6 +366,7 @@ export interface UseSelectProps { onHighlightedIndexChange?: (changes: UseSelectStateChange) => void onStateChange?: (changes: UseSelectStateChange) => void environment?: Environment + inputCleanupDebounceWait?: number; } export interface UseSelectStateChangeOptions