File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ import { useMemo , useRef } from 'react' ;
2
+
3
+ export type Race = < P extends Promise < any > , E = any > ( promise : P , onError ?: ( error : E ) => void ) => P ;
4
+
5
+ const useUnmountPromise = ( ) : Race => {
6
+ const refUnmounted = useRef ( false ) ;
7
+ useRef ( ( ) => ( ) => {
8
+ refUnmounted . current = true ;
9
+ } ) ;
10
+
11
+ const wrapper = useMemo ( ( ) => {
12
+ const race = < P extends Promise < any > , E > ( promise : P , onError ?: ( error : E ) => void ) => {
13
+ const newPromise : P = new Promise ( ( resolve , reject ) => {
14
+ promise . then (
15
+ result => {
16
+ if ( ! refUnmounted . current ) resolve ( result ) ;
17
+ } ,
18
+ error => {
19
+ if ( ! refUnmounted . current ) reject ( error ) ;
20
+ else if ( onError ) onError ( error ) ;
21
+ else console . error ( 'useUnmountPromise' , error ) ;
22
+ }
23
+ ) ;
24
+ } ) as P ;
25
+ return newPromise ;
26
+ } ;
27
+ return race ;
28
+ } , [ ] ) ;
29
+
30
+ return wrapper ;
31
+ } ;
32
+
33
+ export default useUnmountPromise ;
You can’t perform that action at this time.
0 commit comments