Skip to content

Commit

Permalink
Merge pull request #1771 from crimx/patch-3
Browse files Browse the repository at this point in the history
fix useUnmountPromise stops when component is updated
  • Loading branch information
xobotyi authored Mar 10, 2021
2 parents fa9d123 + e3adac0 commit 6ee97ec
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/useUnmountPromise.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useEffect, useMemo, useRef } from 'react';
import { useMemo, useRef } from 'react';
import useEffectOnce from './useEffectOnce';

export type Race = <P extends Promise<any>, E = any>(promise: P, onError?: (error: E) => void) => P;

const useUnmountPromise = (): Race => {
const refUnmounted = useRef(false);
useEffect(() => () => {
useEffectOnce(() => () => {
refUnmounted.current = true;
});

Expand Down
13 changes: 13 additions & 0 deletions tests/useUnmountPromise.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ describe('useUnmountPromise', () => {
]);
expect(res).toBe('UNMOUNTED');
});

it('should resolve promise when component is updated', async () => {
const hook = renderHook(() => useUnmountPromise());

const mounted = hook.result.current;
const pRes = mounted(new Promise(r => setTimeout(() => r(25), 10)));

hook.rerender();

const res = await pRes;

expect(res).toBe(25);
});

it('when component is mounted function should resolve with wrapped promises - 2', async () => {
const hook = renderHook(() => useUnmountPromise());
Expand Down

0 comments on commit 6ee97ec

Please sign in to comment.