-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { useMemo, useRef } from 'react'; | ||
|
||
export type Race = <P extends Promise<any>, E = any>(promise: P, onError?: (error: E) => void) => P; | ||
|
||
const useUnmountPromise = (): Race => { | ||
const refUnmounted = useRef(false); | ||
useRef(() => () => { | ||
refUnmounted.current = true; | ||
}); | ||
|
||
const wrapper = useMemo(() => { | ||
const race = <P extends Promise<any>, E>(promise: P, onError?: (error: E) => void) => { | ||
const newPromise: P = new Promise((resolve, reject) => { | ||
promise.then( | ||
result => { | ||
if (!refUnmounted.current) resolve(result); | ||
}, | ||
error => { | ||
if (!refUnmounted.current) reject(error); | ||
else if (onError) onError(error); | ||
else console.error('useUnmountPromise', error); | ||
} | ||
); | ||
}) as P; | ||
return newPromise; | ||
}; | ||
return race; | ||
}, []); | ||
|
||
return wrapper; | ||
}; | ||
|
||
export default useUnmountPromise; |