File tree 1 file changed +8
-0
lines changed
1 file changed +8
-0
lines changed Original file line number Diff line number Diff line change @@ -17,38 +17,46 @@ export const useRequest = <T>(
17
17
} ) ;
18
18
19
19
useEffect ( ( ) => {
20
+ // Cleanup on unmount
20
21
return ( ) => {
21
22
ref . current . abortController ?. abort ( ) ;
22
23
} ;
23
24
} , [ ] ) ;
24
25
25
26
if ( isEqualWith ( ref . current . deps , deps ) ) {
27
+ // If dependencies haven't changed, return cached state
26
28
return {
27
29
data : ref . current . data ,
28
30
loading : ref . current . state === 'loading' ,
29
31
error : ref . current . error ,
30
32
} ;
31
33
}
32
34
35
+ // Cancel previous request
33
36
ref . current . abortController ?. abort ( ) ;
34
37
38
+ // Update the dependencies and state
35
39
ref . current . deps = deps ;
36
40
ref . current . state = 'loading' ;
37
41
const abortController = new AbortController ( ) ;
38
42
ref . current . abortController = abortController ;
39
43
44
+ // Make the request
40
45
request ( abortController . signal )
41
46
. then ( ( data : T ) => {
47
+ // Only update if the request hasn't been aborted
42
48
if ( abortController . signal . aborted ) return ;
43
49
ref . current . data = data ;
44
50
ref . current . state = 'done' ;
45
51
} )
46
52
. catch ( ( err : unknown ) => {
53
+ // Only update if the request hasn't been aborted
47
54
if ( abortController . signal . aborted ) return ;
48
55
ref . current . error = err ;
49
56
ref . current . state = 'error' ;
50
57
} )
51
58
. finally ( ( ) => {
59
+ // Trigger a re-render to reflect the state changes
52
60
setVersion ( ( v ) => v + 1 ) ;
53
61
} ) ;
54
62
You can’t perform that action at this time.
0 commit comments