Skip to content

Commit cf3644f

Browse files
SyMindotakustay
authored andcommitted
fix(action-pending): prevent state update in unmounted component
1 parent bb49009 commit cf3644f

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

packages/action-pending/src/index.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,27 @@
1-
import {useCallback} from 'react';
1+
import {useCallback, useEffect, useRef} from 'react';
22
import {useCounter} from '@huse/number';
33

44
type AsyncFunction = (...args: any[]) => Promise<any>;
55

66
export function useActionPending<A extends AsyncFunction>(action: A): [A, number] {
7+
const unmounted = useRef(false);
78
const [pendingCount, {inc, dec}] = useCounter();
89
const actionWithPending = useCallback(
910
(...args: Parameters<A>) => {
1011
inc();
1112
const pending = action(...args);
12-
pending.then(dec, dec);
13+
const safeDec = () => {
14+
if (!unmounted.current) {
15+
dec();
16+
}
17+
};
18+
pending.then(safeDec, safeDec);
1319
return pending;
1420
},
1521
[action, dec, inc]
1622
);
23+
useEffect(() => () => {
24+
unmounted.current = true;
25+
}, []);
1726
return [actionWithPending as A, pendingCount];
1827
}

0 commit comments

Comments
 (0)