Created
November 25, 2023 22:38
-
-
Save andrenespolon/9cfc699af2e6f7c81ac364b40fed19e4 to your computer and use it in GitHub Desktop.
Custom react hook usePollingEffect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
export const DEFAULT_POLLING_INTERVAL = 15; | |
type Options = { | |
interval?: number; | |
pollingPersist?: boolean; | |
onCleanUp?: () => void; | |
}; | |
/** | |
* Hook `usePollingEffect` | |
*/ | |
export function usePollingEffect( | |
asyncCallback: (...args: any) => Promise<any> | any, | |
dependencies: any[], | |
options?: Options | |
): void { | |
const timeoutRef = React.useRef<any>(null); | |
const interval = options?.interval | |
? options.interval * 1000 | |
: DEFAULT_POLLING_INTERVAL * 1000; | |
const pollingPersist = | |
typeof options?.pollingPersist !== 'undefined' | |
? options.pollingPersist | |
: true; | |
const onCleanUp = options?.onCleanUp || null; | |
React.useEffect(() => { | |
let stopped = false; | |
/** | |
* Side note: preceding semicolon needed for IIFEs. | |
*/ | |
(async function pollingCallback(): Promise<any> { | |
try { | |
await asyncCallback(); | |
} finally { | |
/** | |
* Set timeout after it finished, unless stopped | |
*/ | |
timeoutRef.current = | |
!stopped && pollingPersist && setTimeout(pollingCallback, interval); | |
} | |
})(); | |
/** | |
* Clean up if dependencies change | |
*/ | |
return (): void => { | |
stopped = true; | |
clearTimeout(timeoutRef.current); | |
if (onCleanUp instanceof Function) { | |
onCleanUp(); | |
} | |
}; | |
}, [...dependencies, pollingPersist, interval, asyncCallback, onCleanUp]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment