Skip to content

Commit

Permalink
fix(useasync): unmount condition
Browse files Browse the repository at this point in the history
  • Loading branch information
namepain committed Jan 17, 2020
1 parent efebbba commit 8d16500
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/useAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,10 @@ export default function useAsync(
}

const run = useCallback(async (...args) => {
console.log(...args)
const uid = ++ref.current.count
try {
setLoading(true)
const value = await ref.current.fn(...args)
console.log('uid ======> ', uid, ref.current.count)
if (uid === ref.current.count) {
setValue(value)
setError(null)
Expand All @@ -53,6 +51,10 @@ export default function useAsync(
// tslint:disable-next-line:no-floating-promises
run(...(deps as DependencyList))
}
// ignore request after unmount
return () => {
++ref.current.count
}
}, [run])

return { loading, value, error, run, cancel }
Expand Down
15 changes: 14 additions & 1 deletion test/useAsync.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ describe('useAsync', () => {
}, deley || 100)
)
}
const { result, rerender, waitForNextUpdate } = renderHook(
const { result, unmount, waitForNextUpdate } = renderHook(
({ fn, deps, immediate }: params) => useAsync(fn, deps, immediate),
{
initialProps: {
Expand Down Expand Up @@ -207,6 +207,19 @@ describe('useAsync', () => {
expect(result.current.value).toBe('reject6')
expect(result.current.error).toBe(null)

// unmount condition
act(() => {
result.current.run('unmount')
})
unmount()

jest.runAllTimers()
expect(fn).toBeCalledTimes(6)
expect(fn1).toBeCalledTimes(6)
expect(result.current.loading).toBe(true)
expect(result.current.value).toBe('reject6')
expect(result.current.error).toBe(null)

jest.useRealTimers()
})
})

0 comments on commit 8d16500

Please sign in to comment.