From 2d17d64d7b054a3b4e437bacc4a6a31c0175432e Mon Sep 17 00:00:00 2001 From: Scott Kyle Date: Tue, 13 Dec 2022 10:41:19 -0800 Subject: [PATCH] Represent correct return type from useDebounce() The return type now correctly reflects that the second item can be called manually as a debounced setter, which is super useful in certain situations. --- src/useDebounce.ts | 4 ++-- test/useDebounce.test.tsx | 9 ++++----- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/useDebounce.ts b/src/useDebounce.ts index 49e05c1..926a6ed 100644 --- a/src/useDebounce.ts +++ b/src/useDebounce.ts @@ -1,5 +1,5 @@ import { useCallback, useRef, useState, Dispatch } from 'react'; -import useDebouncedCallback, { ControlFunctions } from './useDebouncedCallback'; +import useDebouncedCallback, { DebouncedState } from './useDebouncedCallback'; function valueEquality(left: T, right: T): boolean { return left === right; @@ -19,7 +19,7 @@ export default function useDebounce( value: T, delay: number, options?: { maxWait?: number; leading?: boolean; trailing?: boolean; equalityFn?: (left: T, right: T) => boolean } -): [T, ControlFunctions] { +): [T, DebouncedState<(value: T) => void>] { const eq = (options && options.equalityFn) || valueEquality; const [state, dispatch] = useStateIgnoreCallback(value); diff --git a/test/useDebounce.test.tsx b/test/useDebounce.test.tsx index e1a6061..ec03af9 100644 --- a/test/useDebounce.test.tsx +++ b/test/useDebounce.test.tsx @@ -301,13 +301,13 @@ describe('useDebounce', () => { }); it('should preserve debounced object between re-renders', () => { - let cachedDebounced = null; + let cachedDebounced: unknown = null; function Component({ text }) { const [value, debounced] = useDebounce(text, 1000); if (cachedDebounced == null) { cachedDebounced = debounced; } else { - expect(cachedDebounced).toBe(debounced) + expect(cachedDebounced).toBe(debounced); } return
{value}
; } @@ -327,8 +327,7 @@ describe('useDebounce', () => { }); // after runAllTimer text should be updated expect(tree.text()).toBe('Hello world'); - }) - + }); it('should change debounced.isPending to true as soon as the function is called in a sync way', () => { function Component({ text }) { @@ -356,5 +355,5 @@ describe('useDebounce', () => { }); // after runAllTimer text should be updated expect(tree.text()).toBe('Hello world'); - }) + }); });