1- import {
2- useCallback ,
3- useEffect ,
4- useLayoutEffect ,
5- useRef ,
6- useState ,
7- } from 'react'
1+ import { useCallback , useEffect , useRef , useState } from 'react'
82import { useDataLoaderContext } from './DataLoaderProvider'
93import { StatusEnum } from './constants'
104import DataLoader from './dataloader'
@@ -27,20 +21,12 @@ function useDataLoader<ResultType, ErrorType = Error>(
2721 const methodRef = useRef ( method )
2822 const onSuccessRef = useRef ( onSuccess )
2923 const onErrorRef = useRef ( onError ?? onGlobalError )
30- const isMountedRef = useRef ( false )
24+ const needPollingRef = useRef ( needPolling )
3125 const [ , setCounter ] = useState ( 0 )
3226 const forceRerender = useCallback ( ( ) => {
3327 setCounter ( current => current + 1 )
3428 } , [ ] )
3529
36- useLayoutEffect ( ( ) => {
37- isMountedRef . current = true
38-
39- return ( ) => {
40- isMountedRef . current = false
41- }
42- } )
43-
4430 const request = getOrAddRequest ( fetchKey , {
4531 enabled,
4632 method : methodRef . current ,
@@ -77,6 +63,10 @@ function useDataLoader<ResultType, ErrorType = Error>(
7763 [ request ] ,
7864 )
7965
66+ useEffect ( ( ) => {
67+ needPollingRef . current = needPolling
68+ } , [ needPolling ] )
69+
8070 useEffect ( ( ) => {
8171 request . method = method
8272 } , [ method , request ] )
@@ -102,33 +92,30 @@ function useDataLoader<ResultType, ErrorType = Error>(
10292 } , [ enabled , request , keepPreviousData ] )
10393
10494 useEffect ( ( ) => {
105- let timeout : NodeJS . Timeout
106-
107- if (
108- isMountedRef . current &&
109- request &&
110- pollingInterval &&
111- needPolling &&
112- ( request . status === StatusEnum . SUCCESS ||
113- request . status === StatusEnum . ERROR )
114- ) {
115- if (
116- ( typeof needPolling === 'function' && needPolling ( request . data ) ) ||
117- ( typeof needPolling !== 'function' && needPolling )
118- ) {
119- timeout = setTimeout ( ( ) => {
95+ let interval : NodeJS . Timer
96+
97+ if ( pollingInterval ) {
98+ interval = setInterval ( ( ) => {
99+ if (
100+ ( needPollingRef . current &&
101+ typeof needPollingRef . current === 'function' &&
102+ needPollingRef . current ( request . data ) ) ||
103+ ( typeof needPollingRef . current !== 'function' &&
104+ needPollingRef . current &&
105+ ! request . isCalled )
106+ ) {
120107 request
121108 . load ( true )
122109 . then ( onSuccessRef . current )
123110 . catch ( onErrorRef . current )
124- } , pollingInterval )
125- }
111+ }
112+ } , pollingInterval )
126113 }
127114
128115 return ( ) => {
129- if ( timeout && ! isMountedRef . current ) clearTimeout ( timeout )
116+ if ( interval ) clearInterval ( interval )
130117 }
131- } , [ pollingInterval , needPolling , request , request . status , request . data ] )
118+ } , [ pollingInterval , request ] )
132119
133120 return {
134121 data : ! request . isFirstLoading ? request . data : initialData ,
0 commit comments