Skip to content

Commit

Permalink
feat: 🎸 add useUnmountPromise hook
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Dec 7, 2019
1 parent 36a34e8 commit 01421bc
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/useUnmountPromise.ts
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;

0 comments on commit 01421bc

Please sign in to comment.