File tree Expand file tree Collapse file tree 1 file changed +11
-2
lines changed
packages/action-pending/src Expand file tree Collapse file tree 1 file changed +11
-2
lines changed Original file line number Diff line number Diff line change 1
- import { useCallback } from 'react' ;
1
+ import { useCallback , useEffect , useRef } from 'react' ;
2
2
import { useCounter } from '@huse/number' ;
3
3
4
4
type AsyncFunction = ( ...args : any [ ] ) => Promise < any > ;
5
5
6
6
export function useActionPending < A extends AsyncFunction > ( action : A ) : [ A , number ] {
7
+ const unmounted = useRef ( false ) ;
7
8
const [ pendingCount , { inc, dec} ] = useCounter ( ) ;
8
9
const actionWithPending = useCallback (
9
10
( ...args : Parameters < A > ) => {
10
11
inc ( ) ;
11
12
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 ) ;
13
19
return pending ;
14
20
} ,
15
21
[ action , dec , inc ]
16
22
) ;
23
+ useEffect ( ( ) => ( ) => {
24
+ unmounted . current = true ;
25
+ } , [ ] ) ;
17
26
return [ actionWithPending as A , pendingCount ] ;
18
27
}
You can’t perform that action at this time.
0 commit comments