-
Notifications
You must be signed in to change notification settings - Fork 0
/
useCancellablePromiseCleanup.ts
38 lines (34 loc) · 1.26 KB
/
useCancellablePromiseCleanup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { useRef, useEffect, useCallback } from 'react'
import { CaptureCancellablePromise, CancellablePromise } from 'real-cancellable-promise'
/**
* Returns a `capture` function which "captures" `CancellablePromise`'s and
* cancels them when the component unmounts. This is desirable in certain
* situations to prevent callbacks passed down to a component from being called
* after that component is unmounted.
*
* ```
* const capture = useCancellablePromiseCleanup()
*
* // Later, in an async function:
* const result = await capture(api.get('xyz'))
* ```
*/
export function useCancellablePromiseCleanup(): CaptureCancellablePromise {
const cancellablePromisesRef = useRef<CancellablePromise<unknown>[]>([])
// This eslint error is not releveant between the ref does not point to a DOM node
/* eslint-disable react-hooks/exhaustive-deps */
useEffect(
() => (): void => {
for (const promise of cancellablePromisesRef.current) {
promise.cancel()
}
},
[]
)
/* eslint-enable react-hooks/exhaustive-deps */
const capture: CaptureCancellablePromise = useCallback((promise) => {
cancellablePromisesRef.current.push(promise)
return promise
}, [])
return capture
}