Skip to content

Commit

Permalink
fix(useTimeout): isPending never updates
Browse files Browse the repository at this point in the history
  • Loading branch information
jquense committed Jan 2, 2025
1 parent 2cc5518 commit 51e14ec
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 11 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,6 @@
},
"dependencies": {
"dequal": "^2.0.3"
}
},
"packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
12 changes: 6 additions & 6 deletions src/useTimeout.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MutableRefObject, useEffect, useRef, useState } from 'react'
import { MutableRefObject, useEffect, useMemo, useRef, useState } from 'react'
import useMounted from './useMounted'

/*
Expand Down Expand Up @@ -88,7 +88,9 @@ export default function useTimeout() {
}
}, [timeout])

const [returnValue] = useState(() => {
const isPending = !!timeout

return useMemo(() => {
return {
set(fn: () => void, delayMs = 0): void {
if (!isMounted()) return
Expand All @@ -98,10 +100,8 @@ export default function useTimeout() {
clear() {
setTimeoutState(null)
},
isPending: !!timeout,
isPending,
handleRef,
}
})

return returnValue
}, [isPending, setTimeoutState, handleRef, isMounted])
}
13 changes: 9 additions & 4 deletions test/useTimeout.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ describe('useTimeout', () => {
jest.useFakeTimers()

let spy = jest.fn()
let timeout: ReturnType<typeof useTimeout>
let timeout!: ReturnType<typeof useTimeout>

function Wrapper() {
timeout = useTimeout()
Expand All @@ -18,23 +18,25 @@ describe('useTimeout', () => {
render(<Wrapper />)

act(() => {
timeout!.set(spy, 100)
timeout.set(spy, 100)
})

expect(timeout.isPending).toBe(true)
expect(spy).not.toHaveBeenCalled()

act(() => {
jest.runAllTimers()
})

expect(timeout.isPending).toBe(false)
expect(spy).toHaveBeenCalledTimes(1)
})

it('should clear a timeout', () => {
jest.useFakeTimers()

let spy = jest.fn()
let timeout: ReturnType<typeof useTimeout>
let timeout!: ReturnType<typeof useTimeout>

function Wrapper() {
timeout = useTimeout()
Expand All @@ -45,14 +47,17 @@ describe('useTimeout', () => {
render(<Wrapper />)

act(() => {
timeout!.set(spy, 100)
timeout.set(spy, 100)
})

expect(timeout.isPending).toBe(true)

act(() => {
timeout!.clear()
jest.runAllTimers()
})

expect(timeout.isPending).toBe(false)
expect(spy).toHaveBeenCalledTimes(0)
})

Expand Down

0 comments on commit 51e14ec

Please sign in to comment.