Created
August 2, 2021 14:20
-
-
Save zach2825/53c5f398b9dc9b8c33ed818b3e2dd376 to your computer and use it in GitHub Desktop.
react polling hook
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 { 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