Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix useDebounceCallback isPending logic #610

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
5 changes: 5 additions & 0 deletions .changeset/long-balloons-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"usehooks-ts": minor
---

fix useDebounceCallback isPending logic
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,69 @@ describe('useDebounceCallback()', () => {
// The callback should be invoked immediately after flushing
expect(debouncedCallback).toHaveBeenCalled()
})

it('should update isPending on invocations', () => {
const delay = 100
const callback = vitest.fn()
const { result } = renderHook(() => useDebounceCallback(callback, delay))

act(() => {
result.current('test1')
result.current('test2')
})

expect(result.current.isPending()).toBeTruthy()

// Fast-forward time
vitest.advanceTimersByTime(200)

expect(result.current.isPending()).toBeFalsy()
})

it('should update isPending on invocations even if callback errors out', () => {
const delay = 100
const errorMessage =
'Mock implementation throws error for testing purposes.'
const callback = vitest.fn().mockImplementation(() => {
throw new Error(errorMessage)
})
const { result } = renderHook(() => useDebounceCallback(callback, delay))

act(() => {
result.current('test1')
result.current('test2')
})

expect(result.current.isPending()).toBeTruthy()

// Forwarding time will invoke the debounced mock function which throws an error.
expect(() => vitest.advanceTimersByTime(200)).toThrowError(errorMessage)

// Even though the mock implementation threw an error, isPending should still be updated to false.
expect(result.current.isPending()).toBeFalsy()
})

it('should invoke debounced callback even after unmount', () => {
const delay = 100
const debouncedCallback = vitest.fn()
const { result, unmount } = renderHook(() =>
useDebounceCallback(debouncedCallback, delay),
)

act(() => {
result.current('argument')
unmount()
})

// We expect our invocation to still be pending even though the component has already been unmounted.
expect(result.current.isPending()).toBeTruthy()
expect(debouncedCallback).not.toHaveBeenCalled()

// Fast-forward time
vitest.advanceTimersByTime(200)

// Now, long after the component was unmounted, we expect the debounced callback to eventually been called.
expect(result.current.isPending()).toBe(false)
expect(debouncedCallback).toHaveBeenCalled()
})
})
48 changes: 25 additions & 23 deletions packages/usehooks-ts/src/useDebounceCallback/useDebounceCallback.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { useEffect, useMemo, useRef } from 'react'
import { useMemo, useRef } from 'react'

import debounce from 'lodash.debounce'

import { useUnmount } from '../useUnmount'

/** Configuration options for controlling the behavior of the debounced function. */
type DebounceOptions = {
/**
Expand Down Expand Up @@ -76,40 +74,44 @@ export function useDebounceCallback<T extends (...args: any) => ReturnType<T>>(
delay = 500,
options?: DebounceOptions,
): DebouncedState<T> {
const debouncedFunc = useRef<ReturnType<typeof debounce>>()

useUnmount(() => {
if (debouncedFunc.current) {
debouncedFunc.current.cancel()
}
})
const isPendingRef = useRef(false)

const debounced = useMemo(() => {
const debouncedFuncInstance = debounce(func, delay, options)
return useMemo(() => {
const debouncedFunc = debounce(
(...args: Parameters<T>) => {
try {
return func(...args)
} finally {
// Whenever execution of the debounced function has finished, it's execution is not pending anymore,
// even in case of errors.
isPendingRef.current = false
}
},
delay,
options,
)

const wrappedFunc: DebouncedState<T> = (...args: Parameters<T>) => {
return debouncedFuncInstance(...args)
// This code will be executed whenever the client/caller invokes the debounced method,
// so now is the right time to set isPending to true.
isPendingRef.current = true
return debouncedFunc(...args)
}

wrappedFunc.cancel = () => {
debouncedFuncInstance.cancel()
isPendingRef.current = false
debouncedFunc.cancel()
}

wrappedFunc.isPending = () => {
return !!debouncedFunc.current
return isPendingRef.current
}

wrappedFunc.flush = () => {
return debouncedFuncInstance.flush()
isPendingRef.current = false
return debouncedFunc.flush()
}

return wrappedFunc
}, [func, delay, options])

// Update the debounced function ref whenever func, wait, or options change
useEffect(() => {
debouncedFunc.current = debounce(func, delay, options)
}, [func, delay, options])

return debounced
}