1
- import { useEffect , useState , useMemo } from 'react' ;
1
+ import { useEffect , useMemo , useRef , useState } from 'react' ;
2
2
import { FileEventType , FileLike , MemoizedPromise } from '../data' ;
3
3
import { DEFAULT_THROTTLE_TIMEOUT } from '../utils' ;
4
4
5
- export interface UseFileSubscribeOptions {
6
- /** The timeout to throttle initial fetch of value. Default: 500ms. */
7
- throttle ?: number ;
8
- }
9
-
10
5
/**
11
6
* Will subscribe to a value from a file and return the value, as well as any
12
7
* async errors.
13
8
* @param file The file to subscribe to.
14
9
* @param getCurrentValue Function to extract the current value from the file.
15
10
* @param eventType The event type to subscribe. Won't subscribe if not given.
11
+ * @param throttle The timeout to throttle initial fetch of value. Default: 500ms.
16
12
*/
17
13
export function useFileSubscribe < F extends FileLike , T > (
18
14
file : F ,
19
15
getCurrentValue : ( file : F ) => T | MemoizedPromise < T > ,
20
16
eventType ?: FileEventType ,
21
- options : UseFileSubscribeOptions = { } ,
17
+ throttle ?: number ,
22
18
) {
19
+ const getValue = useRef ( getCurrentValue ) ;
20
+
23
21
const [ error , setError ] = useState < any > ( ) ;
24
22
const [ value , setValue ] = useState < T | undefined > ( ( ) => {
25
- const currentValue = getCurrentValue ( file ) ;
23
+ const currentValue = getValue . current ( file ) ;
26
24
if ( currentValue instanceof MemoizedPromise ) return undefined ;
27
25
return currentValue ;
28
26
} ) ;
@@ -43,19 +41,20 @@ export function useFileSubscribe<F extends FileLike, T>(
43
41
const subscribe = ( delay ?: boolean ) => {
44
42
setError ( undefined ) ;
45
43
46
- const val = getCurrentValue ( file ) ;
44
+ const val = getValue . current ( file ) ;
47
45
if ( ! ( val instanceof MemoizedPromise ) ) {
48
46
// Non-memoized-promise, can set directly.
49
47
setValue ( val ) ;
50
48
return ;
51
49
}
52
50
53
- if ( ! delay || val . done || options . throttle === 0 ) {
51
+ setValue ( undefined ) ;
52
+ if ( ! delay || val . done || throttle === 0 ) {
54
53
setMemoValue ( val ) ;
55
54
} else {
56
55
timeout = window . setTimeout ( ( ) => {
57
56
setMemoValue ( val ) ;
58
- } , options . throttle ?? DEFAULT_THROTTLE_TIMEOUT ) ;
57
+ } , throttle ?? DEFAULT_THROTTLE_TIMEOUT ) ;
59
58
}
60
59
} ;
61
60
@@ -70,7 +69,7 @@ export function useFileSubscribe<F extends FileLike, T>(
70
69
cancelled = true ;
71
70
clearTimeout ( timeout ) ;
72
71
} ;
73
- } , [ eventType , file , getCurrentValue , options . throttle ] ) ;
72
+ } , [ eventType , file , throttle ] ) ;
74
73
75
74
return useMemo ( ( ) => [ value , error , setValue ] , [ error , value ] ) ;
76
75
}
0 commit comments