Skip to content

Instantly share code, notes, and snippets.

@zach2825
Created August 2, 2021 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zach2825/53c5f398b9dc9b8c33ed818b3e2dd376 to your computer and use it in GitHub Desktop.
Save zach2825/53c5f398b9dc9b8c33ed818b3e2dd376 to your computer and use it in GitHub Desktop.
react polling hook
import { useState, useEffect } from 'react';
const usePolling = ({
timeoutMs = 5000,
continuePolling,
} = {}) => {
const [ticker, setTicker] = useState(null);
const [onContinuePolling, setOnContinuePolling] = useState(null);
useEffect(() => {
return () => {
setTicker(null);
};
}, []);
useEffect(() => {
(async () => {
if (Number.isInteger(ticker)) {
const response = await onContinuePolling();
console.log({ response });
await new Promise(res => {
setTimeout(res, timeoutMs);
});
// trigger another tick
if (!response) {
setTicker(null);
} else {
if (Number.isInteger(ticker)) {
setTicker(ticker + 1);
}
}
}
})();
}, [ticker]);
const startPolling = async ({ continuePolling: _continuePolling = continuePolling }) => {
setOnContinuePolling(() => _continuePolling);
setTicker(0);
};
const stopPolling = () => {
setTicker(null);
};
return [{ ticker }, { startPolling, stopPolling }];
};
export default usePolling;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment